Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby 2.0 named parameters from a hash

Tags:

ruby

ruby-2.0

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.

Update:

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])

like image 819
Christian Schlensker Avatar asked May 03 '13 22:05

Christian Schlensker


People also ask

How do you pass a named parameter in Ruby?

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.

How do you call a hash value in Ruby?

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.

What is * args in Ruby?

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).


1 Answers

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"
like image 102
Chris Heald Avatar answered Oct 05 '22 23:10

Chris Heald