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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With