Ruby 2.0 with parameters from the hash

If I have a method in ruby ​​that takes named arguments ...

def smoosh(first: nil, second: nil) first + second end 

The easiest way to pass a hash to this method if the keys match:

 params = { first: 'peanut', second: 'butter' } smoosh(params) 

The above argument error.

Update:

It looks like this might be a problem with the Sinatra options.

When I do this:

 get 'a_sinatra_route' do hash = params.clone hash.symbolize_keys! smoosh(hash) end 

It works great. This does not work when you just pass the parameters yourself. (even if you can access individual parameters using the params[:attr] symbol key)

+4
source share
2 answers

Everything seems to work fine for me.

 2.0.0p0 :007 > def smoosh(first: nil, second: nil) 2.0.0p0 :008?> first + second 2.0.0p0 :009?> end => nil 2.0.0p0 :010 > params = { first: 'peanut', second: 'butter' } => {:first=>"peanut", :second=>"butter"} 2.0.0p0 :012 > smoosh(params) => "peanutbutter" 
+9
source

It throws an ArgumentError because you pass one hash to a method that takes two arguments - even if the hash has two key / value pairs, this is another argument!

In this situation, you can try:

 smoosh(params[:first], params[:second]) 

To pass values.

-6
source

Source: https://habr.com/ru/post/1479076/


All Articles