Concise Ruby hash equivalent of Python dict.get()

十年热恋 提交于 2021-01-26 23:34:01

问题


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?


回答1:


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"}



回答2:


An alternative to #fetch is to simply do something like this:

h[:x] || 5

In Python missing keys will raise a KeyError, but in Ruby missing keys simply return nil.

This has a subtly different meaning, because the default will happen if either:

  1. the key is not in the hash
  2. the key's value in the hash is already nil

whereas fetch will only make an impact in scenario 1.

The closest Python equivalent of this code is

h.get('x') or 5

(Note though that this is still different since truthiness/falsiness is different in Python than in Ruby)



来源:https://stackoverflow.com/questions/20258632/concise-ruby-hash-equivalent-of-python-dict-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!