Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use an array as default values for Ruby Hash? [duplicate]

Tags:

ruby

hash

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
 => {}
like image 423
Cheng Avatar asked Mar 30 '11 16:03

Cheng


People also ask

How might you specify a default value for a 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?

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.

Are Hashes indexed ruby?

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.

What is Ruby hash object?

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.


1 Answers

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.

like image 89
Marc-André Lafortune Avatar answered Oct 05 '22 06:10

Marc-André Lafortune