Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of using `Hash#fetch` over `Hash#[]`

Tags:

I am not sure in what situation I would want to use Hash#fetch over Hash#[]. Is there a common scenario in where it would be of good use?

like image 482
Eduardo Bautista Avatar asked Jan 30 '13 01:01

Eduardo Bautista


People also ask

What is hash usually used for?

Hash functions and their associated hash tables are used in data storage and retrieval applications to access data in a small and nearly constant time per retrieval. They require an amount of storage space only fractionally greater than the total space required for the data or records themselves.

What is the safest hash?

Common attacks like brute force attacks can take years or even decades to crack the hash digest, so SHA-2 is considered the most secure hash algorithm.


1 Answers

Three main uses:

  1. When the value is mandatory, i.e. there is no default:

    options.fetch(:repeat).times{...} 

    You get a nice error message too:

    key not found: :repeat 
  2. When the value can be nil or false and the default is something else:

    if (doit = options.fetch(:repeat, 1))   doit.times{...} else   # options[:repeat] is set to nil or false, do something else maybe end 
  3. When you don't want to use the default/default_proc of a hash:

    options = Hash.new(42) options[:foo] || :default # => 42 options.fetch(:foo, :default) # => :default 
like image 159
Marc-André Lafortune Avatar answered Nov 06 '22 00:11

Marc-André Lafortune