Mateu
Mateu

Reputation: 2698

Ruby: adding hash of params to params of a function: looking for a cleaner solution

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

Answers (1)

Beat Richartz
Beat Richartz

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:

  • It is common to use underlined notation and not camelCase for local variables in ruby, so params_hash and not paramsHash.
  • Spaces for between the assignment operator, the variable getting assigned and the assignment are common: result = 'this' and not result='this'
  • Same with the key-value pairs in Hashes: {: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

Related Questions