Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a ruby method that accepts a hash of parameters

Tags:

ruby

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?

like image 417
collimarco Avatar asked Feb 24 '09 20:02

collimarco


People also ask

How do you iterate through a Hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

How do you create a Hash in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.

How do I get the Hash value in Ruby?

Convert the key from a string to a symbol, and do a lookup in the hash. Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases.

What Hash function does Ruby use?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.


2 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 
like image 151
Allyn Avatar answered Oct 05 '22 09:10

Allyn


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

like image 42
scottd Avatar answered Oct 05 '22 09:10

scottd