如何为散列中的未初始化键增加值?

lab*_*nth 8 ruby hashtable

如果我尝试增加哈希中尚不存在的键的值,就像这样

h = Hash.new
h[:ferrets] += 1
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

NoMethodError: undefined method `+' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

这对我来说很有意义,而且我知道这一定是一个非常简单的问题,但是我很难在SO上找到它.如果我事先不知道我将拥有哪些按键,如何添加和增加这些按键?

ymo*_*nad 19

你可以在构造函数中设置hash的默认值

h = Hash.new(0)
h[:ferrets] += 1
p h[:ferrets]
Run Code Online (Sandbox Code Playgroud)

请注意,设置默认值有一些缺陷,因此您必须小心使用它.

h = Hash.new([]) # does not work as expected (after `x[:a].push(3)`, `x[:b]` would be `[3]`)
h = Hash.new{[]} # also does not work as expected (after `x[:a].push(3)`  `x[:a]` would be `[]` not `[3]`)
h = Hash.new{Array.new} # use this one instead
Run Code Online (Sandbox Code Playgroud)

因此||=在某些情况下使用可能很简单

h = Hash.new
h[:ferrets] ||= 0
h[:ferrets] += 1
Run Code Online (Sandbox Code Playgroud)


Joh*_*n C 7

解决此问题的一种方法是为您的哈希设置默认值:

h = Hash.new
h.default = 0
h[:ferrets] += 1

puts h.inspect
#{:ferrets=>1}
Run Code Online (Sandbox Code Playgroud)

散列的默认默认值是 nil,并且 nil 不了解如何 ++ 本身。

h = Hash.new{0} 
h = Hash.new(0) # also works (thanks @Phrogz)
Run Code Online (Sandbox Code Playgroud)

是另一种在声明时设置默认值的方法。

  • 请注意,这里没有理由使用块形式。尝试`Hash.new(0)`。 (2认同)