Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash initialization (default value nil)

Tags:

ruby

hash

I've been reading the Ruby docs, and looking at some other posts on the issue, but I am still wondering about this:

#counts each number in an array once
array = [1,1,2,5,3,2,5,3,3,3]
numbers = {}
array.each { |num| numbers[num] += 1 }

=> in `block in mode': undefined method `+' for nil:NilClass (NoMethodError)

In the Hash documentation the default value for a Hash is nil, which is why I am getting this error I assume. Is there a better way to insert each key/(value += 1) into the numbers array?

like image 900
oconn Avatar asked Nov 06 '13 03:11

oconn


People also ask

How might you specify a default value for a Hash?

From the doc, setting a default value has the following behaviour: Returns the default value, the value that would be returned by hsh if key did not exist in hsh. See also Hash::new and Hash#default=. Therefore, every time frequencies[word] is not set, the value for that individual key is set to 0.

How do you initialize a Hash in Ruby?

Another initialization method is to pass Hash. new a block, which is invoked each time a value is requested for a key that has no value. This allows you to use a distinct value for each key. The block is passed two arguments: the hash being asked for a value, and the key used.

How do you define a Hash in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.


2 Answers

Try passing a default value to your new hash as such

numbers = Hash.new(0)
like image 87
squiguy Avatar answered Oct 18 '22 03:10

squiguy


You can explicitly do it this way as well:

array.each { |num| numbers[num] = (numbers[num] || 0) + 1 }
like image 30
Candide Avatar answered Oct 18 '22 04:10

Candide