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?
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.
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.
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.
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.
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.
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