Reputation: 2698
I need to call a function which its params is a hash. For its params I have a hash, and an attribute that I need to merge. To do so, I use the following, which works correctly:
paramsHash={:att1=> "1", :att2=>"2"} #this is obtained from a function
result=MyClass.where({:att0=> "0"}.merge(paramsHash))
As said, this works, no problem there. My question is, is there a nice ruby fancy way to to this? Something like
paramsHash={:att1=> "1", :att2=>"2"} #this is obtained from a function
result=MyClass.where(:att0=> "0", paramsHash.as_params)
Thanks
Upvotes: 0
Views: 94
Reputation: 9622
There is no fancier way to do this than merge
, I just would write it the other way around so you can relieve the curly braces:
result = MyClass.where(params_hash.merge(att0: "0"))
This is the fanciest way I can think of writing your code. It does however change the way the hashes get merged, which makes no difference in the code you presented in your question, but may make a difference if the same key is present in both hashes.
Other things to make your ruby fancier:
params_hash
and not paramsHash
.result = 'this'
and not result='this'
{:this => 'is a hash'}
and not {:this=>'is a hash'}
in ruby 1.9., you can even do {this: 'is a hash'}
, which is ruby 1.9 notation for symbols as hash keys.Some rubyists like to relieve the optional braces, you can do that too if you like:
result = MyClass.where params_hash.merge(att0: "0")
or
result = MyClass.where(params_hash.merge att0: "0")
Upvotes: 2