conditions[:foo] = params[:foo] if params[:foo].present? It will only create a key-value pair in the conditions hash if the key-value pair is present in params.
Is there a way to write it shorter? I was thinking about Hash#fetch:
conditions[:foo] = params.fetch(:foo, nil) But it is not what I want, because then I'll get a pair with nil value, if there is no such key in params.
I only need the conditions key-value created if such a key-value is present in params.
I am asking the question because I have a few similar lines of assigning, where params[:foo] is repeated twice on each line:
conditions[:foo] = params[:foo] if params[:foo].present? conditions[:bar] = params[:bar] if params[:bar].present? conditions[:baz] = params[:baz] if params[:baz].present? conditions[:zxc] = params[:zxc] if params[:zxc].present? # ...
params = {foo: "foo", bar: "bar"}then which keys and values you wanted to store inconditions?.params[:foo], you can do it withselectandmerge!, but it's uglier and slower.params[:foo]irritates me :)