If you find yourself involved in many of them, you can write a small 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 hashes of the source and destination often matches what 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 can simply paste the values โโinto the Hash and then remove the hash at the end to remove all keys with a null value:
filters.delete_if { |k, v| v.nil? }
mikej source share