简明的Ruby哈希等效于Python dict.get() [英] Concise Ruby hash equivalent of Python dict.get()

查看:42
本文介绍了简明的Ruby哈希等效于Python dict.get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

在Python中,我曾经

In Python, I used to

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

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

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

推荐答案

是的,它被称为

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

这篇关于简明的Ruby哈希等效于Python dict.get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆