Create a ruby method that accepts a hash of parameters

Solution 1:

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:

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:

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