相关疑难解决方法(0)

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

知道我可以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中是否有相同的方法?

ruby python hash dictionary

9
推荐指数
1
解决办法
3587
查看次数

标签 统计

dictionary ×1

hash ×1

python ×1

ruby ×1