开发者

Clean way to assign value unless empty

I often need to assign a variable, if the source value is set. So far I have done it like this:

filters[:red] = params[:search][:red] unless params[:search][:red].nil?

This works but looks a bit clumsy. There must be a more DRY way of getting this result.

Any suggestions?

Bes开发者_开发技巧t regards. Asbjørn Morell.


If you find yourself doing a lot of these you could write a little helper method:

def set_unless_nil(hsh, key, val)
  hsh[key] = val unless val.nil?
end

and then:

set_unless_nil filters, :red, params[:search][:red]

And if the key in the source and destination hashes is frequently the same you could write:

def copy_key_unless_nil(src_hash, key, dest_hash)
  dest_hash[key] = src_hash[key] unless src_hash[key].nil?
end

and then:

copy_key_unless_nil params[:search], :red, filters

Alternatively you could just set the values into the Hash anyway and then tidy the hash at the end to remove all the keys with a nil value:

filters.delete_if { |k, v| v.nil? }


It's already pretty good, but it could be a little dry-er

red=params[:search][:red]
filters[:red]=red if red

it looks a little bit neater this way and will still work as you intend. Always remember you can rewrite:

unless x.nil?

as:

if x

they will evaluate the same, but the latter is slightly more ambiguous and cleaner


If params[:search][:red] can only be nil because it is not in the hash, I'd use params[:search].has_key?(:red) so that a casual reader can understand what the situation is better.


If params[:search][:red] can only be nil because it is not in the hash, and assuming you want to copy everything in params[:search] to filters, then:

filters.merge!(params[:search])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜