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.
If you find yourself doing a lot of these you could write a little helper method:
and then:
And if the key in the source and destination hashes is frequently the same you could write:
and then:
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: