A clean way to assign a value if 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? 

It works, but it looks a bit awkward. There should be a more severe way to get this result.

Any suggestions?

Sincerely. Asbjรถrn Morell.

+4
source share
4 answers

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? } 
+2
source

This is already very good, but it may be a little dry er

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

it looks a little neat this way and will still work the way you plan. Always remember that you can rewrite:

 unless x.nil? 

as:

 if x 

they will evaluate the same thing, but the latter is a bit more ambiguous and cleaner

0
source

If params[:search][:red] can only be nil because it is not in the hash, I would use params[:search].has_key?(:red) so that a casual reader can figure out which is better.

0
source

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

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

Source: https://habr.com/ru/post/1311795/


All Articles