Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise Ruby hash equivalent of Python dict.get()

In know that I can manipulate a Ruby default Hash value like this:

h={a:1, b:2, c:3}
h[:x] # => nil
h.default = 5
h[:x] # => 5
h.default = 8
h[:y] # => 8

but this gets quite tedious when doing it repeatedly for multiple values with different defaults.

It also could get dangerous if the hash is passed to other methods which want their own defaults for certain (potentially missing) keys.

In Python, I used to

d={'a':1, 'b':2, 'c':3}
d.get('x', 5) # => 5
d.get('y', 8) # => 8

which doesn't have any side-effects. Is there an equivalent of this get method in Ruby?

like image 751
FriendFX Avatar asked Nov 28 '13 05:11

FriendFX


Video Answer


1 Answers

Yes, it is called fetch, and it can also take a block:

h.fetch(:x, 5)
h.fetch(:x) {|missing_key| "Unfortunately #{missing_key} is not available"}
like image 161
Sean Vieira Avatar answered Oct 13 '22 10:10

Sean Vieira