ruby 如果键不存在创建默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9108619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If key does not exist create default value
提问by Steve
Can anyone show me a ruby way of checking if a key exists in a hash and if it does not then give it a default value. I'm assuming there is a one liner using unless to do this but I'm not sure what to use.
任何人都可以向我展示一种检查密钥是否存在于散列中的ruby 方法,如果不存在,则为其提供默认值。我假设除非这样做,否则使用单衬,但我不确定使用什么。
回答by Michael Kohl
If you already have a hash, you can do this:
如果你已经有一个哈希,你可以这样做:
h.fetch(key, "default value")
Or you exploit the fact that a non-existing key will return nil:
或者您利用不存在的密钥将返回的事实nil:
h[key] || "default value"
To create hashes with default values it depends on what you want to do exactly.
要使用默认值创建散列,这取决于您想要做什么。
Independent of key and will not be stored:
h = Hash.new("foo") h[1] #=> "foo" h #=> {}Dependent on the key and will be stored:
h = Hash.new { |h, k| h[k] = k * k } h[2] #=> 4 h #=> {2=>4}
独立于密钥并且不会被存储:
h = Hash.new("foo") h[1] #=> "foo" h #=> {}取决于密钥并将被存储:
h = Hash.new { |h, k| h[k] = k * k } h[2] #=> 4 h #=> {2=>4}
回答by nkm
Constructor of Hash class accept a default value, same will be returned if a matching key is not found.
Hash 类的构造函数接受一个默认值,如果没有找到匹配的键,将返回相同的值。
h = Hash.new("default")
h.has_key?("jake")
=> false
h["jake"]
=> "default"
h["jake"] = "26"
h.has_key?("jake")
=> true
回答by KL-7
If you don't need to store that default value into hash you can use Hash#fetchmethod:
如果您不需要将该默认值存储到哈希中,您可以使用Hash#fetch方法:
hash = {}
hash.fetch(:some_key, 'default-value') # => 'default-value'
p hash
# => {}
If you need in addition to store your default value every time you access non-existent key and you're the one initializing the hash you can do it using Hash#newwith a block:
如果您还需要在每次访问不存在的密钥时存储您的默认值,并且您是初始化哈希的人,您可以使用Hash#new一个块来完成它:
hash = Hash.new { |hash, key| hash[key] = 'default-value' }
hash[:a] = 'foo'
p hash[:b]
# => 'default-value'
p hash
# => { :a => 'foo', :b => 'default-value' }
回答by Matthijs
You can use the ||=operator:
您可以使用||=运算符:
hash = {some_key: 'some_value'}
puts hash[:some_key] ||= 'default_value' # prints 'some_value'
puts hash[:non_existing_key] ||= 'default_value' # prints 'default_value'
puts hash.inspect # {:some_key=>"some_value", :non_existing_key=>"default_value"}
回答by phatmann
If you are storing a default value that might be nil and you need to calculate it at storage time:
如果您存储的默认值可能为零,并且需要在存储时计算它:
hash = {}
...
hash.fetch(key) {|k| hash[k] = calc_default()}

