views:

1020

answers:

2

I know this may be a stupid question, but I don't know how to create a ruby function that accepts a hash of parameters. I mean, in Rails I'd like to use a function like this:

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

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

Thanks in advance!

+7  A: 

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
Allyn
Can't I use something like login_success(*params)?
collimarco
a * (aka splat operator) means that method accepts any number of args and will put them in an array called params. Deciding on whether to use it or not depends on what you're after. In the example you provided, a hash makes sense.
Allyn
That says you are expecting any number of arguments. Like `foo(1, :b, '3')`. Also, you don't need the "={}" part of that. this will work fine: def login_success(hash). The above code just sets the default as an empty hash.
Squeegy
Now it's clear. Thank you for your replies!
collimarco
+8  A: 

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

ScottD