I face a weirb problem with optionals parameters in ruby.
This is my code :
def foo options={:test => true}
puts options[:test]
end
foo # => puts true
foo :lol => 42 # => puts nil
I can not figure out why the second call puts nil.
Is seems that putting an other parameter set :test to nil.
Thanks.
It happens because if it is a default parameter, passing a hash parameter will completely overwrite it (ie. it sets
options = {:lol => 42}), so theoptions[:test]key no longer exists.To give particular hash keys default values, try:
In this case, we merge a hash with default values for certain keys (
{:test => true}), with another hash (containing the key=>values in the argument). If a key occurs in both hash objects, the value in the hash passed to themergefunction will take precedence.