RUBY: 如何匹配散列中的 nil 值

RUBY: How to match a nil value in a hash

我想问你如何匹配散列中的 nil 值,e。 g.:

aAnimals = {1=>'dog', 2=>'cat'}
puts laAnimals[1]  # dog
puts laAnimals[2]  # cat
puts laAnimals[3]  # nil

如果值为 nil 或高于矩阵的长度,我如何放置 'no animal',例如:

laAnimals = {1=>'dog', 2=>'cat'}
laAnimals.default = 'no animal'

puts laAnimals[1]  # dog
puts laAnimals[2]  # cat
puts laAnimals[3]  # no animal

我想要这样的东西:laAnimals = {1=>'dog', 2=>'cat', default='no animal'}...这可能吗?

来自http://ruby-doc.org/core-2.2.0/Hash.html

Hashes have a default value that is returned when accessing keys that do not exist in the hash. If no default is set nil is used. You can set the default value by sending it as an argument to ::new:

因此在您的情况下使用 laAnimals = Hash.new("no animal") 将使用字符串 no animal 作为默认值。

Exupery 的回答是正确的,但如果您无法访问正在使用的哈希的创建,则可以使用 Hash#fetch (docs).

laAnimals = {1=>'dog', 2=>'cat'}
puts laAnimals.fetch(1, 'no animal')  # dog
puts laAnimals.fetch(2, 'no animal')  # cat
puts laAnimals.fetch(3, 'no animal')  # 'no animal'

我个人更喜欢这种访问哈希的方式,因为如果密钥(在您的示例中,12)不存在,它将引发异常。