Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing hashes instead of method parameters [closed]

I see that in Ruby (and dynamically typed languages, in general) a very common practice is to pass a hash, instead of declaring concrete method parameters. For example, instead of declaring a method with parameters and calling it like this:

def my_method(width, height, show_border) my_method(400, 50, false) 

you can do it this way:

def my_method(options) my_method({"width" => 400, "height" => 50, "show_border" => false}) 

I'd like to know your opinion about it. Is it a good or a bad practice, should we do it or not? In what situation using this practice is valid, and it what situation can it be dangerous?

like image 419
rmaruszewski Avatar asked Dec 18 '09 09:12

rmaruszewski


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.

Are Ruby hashes ordered?

Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.

What are Ruby hashes?

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.

What is key and value in hash?

The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.


1 Answers

Ruby has implicit hash parameters, so you could also write

def my_method(options = {})   my_method(:width => 400, :height => 50, :show_border => false) 

and with Ruby 1.9 and new hash syntax it can be

my_method( width: 400, height: 50, show_border: false ) 

When a function takes more than 3-4 parameters, it's much easier to see which is what, without counting the respective positions.

like image 74
MBO Avatar answered Sep 20 '22 22:09

MBO