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?
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.
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.
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.
Try passing a default value to your new hash as such
numbers = Hash.new(0)
You can explicitly do it this way as well:
array.each { |num| numbers[num] = (numbers[num] || 0) + 1 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With