简洁的Ruby哈希等价的Python dict.get()

Fri*_*dFX 9 ruby python hash dictionary

知道我可以Hash像这样操作Ruby默认值:

h={a:1, b:2, c:3}
h[:x] # => nil
h.default = 5
h[:x] # => 5
h.default = 8
h[:y] # => 8
Run Code Online (Sandbox Code Playgroud)

但是,对于具有不同默认值的多个值重复执行此操作时,这会非常繁琐.

如果将散列传递给其他需要某些(可能缺少的)键的默认值的方法,它也会变得危险.

在Python中,我曾经

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

没有任何副作用.get在Ruby中是否有相同的方法?

Sea*_*ira 23

是的,它被调用fetch,它也可以采取一个块:

h.fetch(:x, 5)
h.fetch(:x) {|missing_key| "Unfortunately #{missing_key} is not available"}
Run Code Online (Sandbox Code Playgroud)