If I have a method in ruby that takes named arguments...
def smoosh(first: nil, second: nil)
first + second
end
Whats the easiest way to pass a hash to that method if the keys match:
params = { first: 'peanut', second: 'butter' }
smoosh(params)
The above produces an argument error.
It seems like this might be an issue with how Sinatra parameters work.
When I do:
get 'a_sinatra_route' do
hash = params.clone
hash.symbolize_keys!
smoosh(hash)
end
It works fine. It does not work when just passing the params in by themselves. (even though you can access the individual params with the symbol key params[:attr]
)
You can define the default value and the name of the parameter and then call the method the way you would call it if you had hash-based "named" parameters but without the need to define defaults in your method. You would need this in your method for each "named parameter" if you were using a hash. Save this answer.
Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
Seems to work just 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With