tags:

views:

67

answers:

4

Hello,

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?

Best regards. Asbjørn Morell.

+1  A: 

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? }
mikej
A: 

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

mpd
`unless x.nil?` and `if x` are not equivalent if `x == false`
mikej
A: 

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.

Andrew Grimm
A: 

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])
Wayne Conrad