Will someone please explain options hashes? I am working through the ruby course from testfirst.org. Exercise 10 (temperature_object) requires knowledge of options hashes.
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
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, 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.
Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
Options hash is a nice concept enabled by a feature of ruby parser. Say, you have a method with some required arguments. Also you may pass some optional arguments. Over time you may add more optional arguments or remove old ones. To keep method declaration clean and stable, you can pass all those optional arguments in a hash. Such method would look like this:
def foo(arg1, arg2, opts = {}) opts.to_s # just return a string value of opts end
So it has two required values and last argument with default value of hash. If you don't have any optional arguments to pass, you call it like this:
foo(1, 2) # => "{}"
If you do have something optional, you call it like this:
foo(1, 2, {truncate: true, redirect_to: '/'}) # => "{:truncate=>true, :redirect_to=>\"/\"}"
This code is so idiomatic to ruby that its parser actually allows you to omit curly braces when passing hash as a last argument to a method:
foo(1, 2, truncate: true, redirect_to: '/') # => "{:truncate=>true, :redirect_to=>\"/\"}"
If you use rails, for example, you'll see options hashes everywhere. Here, I opened just a random controller in my app:
class ProductsController < ApplicationController before_filter :prepare_search_params, only: :index # ^^^^^^^^^^ options hash here
So, in short: options hash is argument of a method which is located last and has default value of {}
. And you normally pass hashes to it (hence the name).
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