I was adding items to a Hash key. I was expecting to get a structure like this:
{
'a' : [1],
'b' : [2, 3, 4]
}
I used an Array to initialize the Hash.
irb> hash = Hash.new([])
=> {}
Then started using it:
irb> hash['a'] << 1
=> [1]
irb> hash['b'] << 2
=> [1, 2]
But it turns out:
irb> hash
=> {}
Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil . Creates a new hash populated with the given objects. Equivalent to the literal { key, value, ... } .
Can a hash have multiple values Ruby? Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
A Hash is a collection of key-value pairs. It is similar to an Array , except that indexing is done via arbitrary keys of any object type, not an integer index.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.
Try the following instead:
hash = Hash.new{|h, k| h[k] = []}
hash['a'] << 1 # => [1]
hash['b'] << 2 # => [2]
The reason you got your unexpected results is that you specified an empty array as default value, but the same array is used; no copy is done. The right way is to initialize the value with a new empty array, as in my code.
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