Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch vs. [] when working with hashes? [duplicate]

Tags:

ruby

From Ruby Koans about_hashes.rb:

Why might you want to use #fetch instead of #[] when accessing hash keys?

like image 732
aljabear Avatar asked May 15 '13 15:05

aljabear


People also ask

What is hash fetch?

Hash#fetch() is a Hash class method which returns a value from the hash for the given key. With no other arguments, it will raise a KeyError exception. Syntax: Hash.fetch() Parameter: Hash values. Return: value from the hash for the given key.

Why might you want to use #fetch instead of #[] when accessing hash keys Ruby?

By default, using #[] will retrieve the hash value if it exists, and return nil if it doesn't exist *. Using #fetch gives you a few options (see the docs on #fetch): fetch(key_name) : get the value if the key exists, raise a KeyError if it doesn't.

Are nested hashes possible in Ruby?

The hashes that you've seen so far have single key/value pairs. However, just like arrays, they can be nested, or multidimensional.

What is a ruby Hash?

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.


2 Answers

By default, using #[] will retrieve the hash value if it exists, and return nil if it doesn't exist *.

Using #fetch gives you a few options (see the docs on #fetch):

  • fetch(key_name): get the value if the key exists, raise a KeyError if it doesn't
  • fetch(key_name, default_value): get the value if the key exists, return default_value otherwise
  • fetch(key_name) { |key| "default" }: get the value if the key exists, otherwise run the supplied block and return the value.

Each one should be used as the situation requires, but #fetch is very feature-rich and can handle many cases depending on how it's used. For that reason I tend to prefer it over accessing keys with #[].

* As Marc-André Lafortune said, accessing a key with #[] will call #default_proc if it exists, or else return #default, which defaults to nil. See the doc entry for ::new for more information.

like image 116
Jon Cairns Avatar answered Oct 06 '22 23:10

Jon Cairns


With [], the creator of the hash controls what happens when a key does not exist, with fetch you do.

like image 27
Jörg W Mittag Avatar answered Oct 07 '22 01:10

Jörg W Mittag