Create a ruby ​​method that takes a hash of parameters

I know this might be a dumb question, but I don't know how to create a ruby ​​method that accepts a hash of parameters. I mean, in Rails, I would like to use a method like this:

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

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

+55
ruby
Feb 24 '09 at 20:23
source share
4 answers

If you pass parameters to the Ruby function in the hash syntax, Ruby will assume that this is your goal. In this way:

 def login_success(hsh = {}) puts hsh[:msg] end 
+59
Feb 24 '09 at 20:25
source share

Keep in mind that you can execute the syntax when you do not consider the hash characters {} if the hash parameter is the last parameter of the function. So you can do what Allin did, and it will work. Also

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

And you can call him

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

But if the hash is not the last parameter, you must surround the hash elements with {}.

+30
Feb 24 '09 at 20:54
source share

Use one single argument. Ruby converts named values ​​to 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 that you get the hash, instead of typing in ruby-uti, you will need to manage 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 
+5
Feb 26 '13 at 14:56
source share

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 the defaults,

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

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

+5
Apr 30 '15 at 13:36
source share



All Articles