Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do methods use hash arguments in Ruby?

I saw hash arguments used in some library methods as I've been learning.

E.g.,

list.search(:titles, genre: 'jazz', duration_less_than: 270) 

Can someone explain how a method uses arguments like this, and how you could create a method that makes use of Hash arguments?

like image 495
Senjai Avatar asked May 15 '13 23:05

Senjai


People also ask

How do you pass hash as an argument in Ruby?

As of Ruby 2.7 now, implicit hash parameters are deprecated and will be removed in Ruby 3.0 – means, we need again the {…} explicitly to pass a hash (see). The Ruby 1.9 syntax shown here is still possible for calling a method with keyword parameters.

What does * args mean in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

How do you access the hash in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

What is hash in Ruby on Rails?

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.


1 Answers

Example:

def foo(regular, hash={})     puts "regular: #{regular}"     puts "hash: #{hash}"     puts "a: #{hash[:a]}"     puts "b: #{hash[:b]}" end  foo("regular argument", a: 12, :b => 13) 

I use hash={} to specify that the last argument is a hash, with default value of empty hash. Now, when I write:

foo("regular argument", a: 12, :b => 13) 

It's actually a syntactic sugar for:

foo("regular argument", {a: 12, :b => 13}) 

Also, {a: 12} is syntactic sugar for {:a => 12}.

When all of this is combined together, you get a syntax that looks similar to named arguments in other languages.

like image 167
Idan Arye Avatar answered Sep 19 '22 08:09

Idan Arye