Home » Ruby » Create a ruby method that accepts a hash of parameters

Create a ruby method that accepts a hash of parameters

Posted by: admin November 30, 2017 Leave a comment

Questions:

I know this may be a stupid question, but 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?

Answers:

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

Questions:
Answers:

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 {}.

Questions:
Answers:

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

Questions:
Answers:

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