0

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.

1

1 Answer 1

1

It happens because if it is a default parameter, passing a hash parameter will completely overwrite it (ie. it sets options = {:lol => 42}), so the options[:test] key no longer exists.

To give particular hash keys default values, try:

def foo options={} options = {:test => true}.merge options puts options[:test] end 

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 the merge function will take precedence.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.