Create a ruby method that accepts a hash of parameters

Ruby

Ruby Problem Overview


I don't know how to create a ruby method that accepts a hash of parameters. I mean, in Rails I'd like to use a method like this:

login_success :msg => "Success!", :gotourl => user_url

What is the prototype of a method that accepts this kind of parameters? How do I read them?

Ruby Solutions


Solution 1 - Ruby

If you pass paramaters to a Ruby function in hash syntax, Ruby will assume that is your goal. Thus:

def login_success(hsh = {})
  puts hsh[:msg]
end

Solution 2 - Ruby

A key thing to remember is that you can only do the syntax where you leave out the hash characters {}, if the hash parameter is the last parameter of a function. So you can do what Allyn did, and that will work. Also

def login_success(name, hsh)
  puts "User #{name} logged in with #{hsh[:some_hash_key]}"
end

And you can call it with

login_success "username", :time => Time.now, :some_hash_key => "some text"

But if the hash is not the last parameter you have to surround the hash elements with {}.

Solution 3 - Ruby

With the advent of Keyword Arguments in Ruby 2.0 you can now do

def login_success(msg:"Default", gotourl:"http://example.com")
  puts msg
  redirect_to gotourl
end

In Ruby 2.1 you can leave out the default values,

def login_success(msg:, gotourl:)
  puts msg
  redirect_to gotourl
end

When called, leaving out a parameter that has no default value will raise an ArgumentError

Solution 4 - Ruby

Use one single argument. Ruby will transform the named values into a hash:

def login_success arg
 # Your code here
end

login_success :msg => 'Success!', :gotourl => user_url
# => login_success({:msg => 'Success!', :gotourl => user_url})

If you really want to make sure you get a hash, instead of the default ruby duck typing, then you would need to control for it. Something like, for example:

def login_success arg
  raise Exception.new('Argument not a Hash...') unless arg.is_a? Hash
  # Your code here
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncollimarcoView Question on Stackoverflow
Solution 1 - RubyAllynView Answer on Stackoverflow
Solution 2 - RubyscottdView Answer on Stackoverflow
Solution 3 - Rubyuser160917View Answer on Stackoverflow
Solution 4 - RubyCCDView Answer on Stackoverflow