2

Given this code:

h = Hash.new([])

3.times do |i|
  h[:a] << i
end

I expect h to be {:a => [0, 1, 2]}, but it is empty. What am I doing wrong?

Christoph Petschnig
  • 4,047
  • 1
  • 37
  • 46

1 Answers1

7

As the API says:

If obj is specified, this single object will be used for all default values.

With a small rewrite of your code, it should become clear what happens:

a = []
h = Hash.new(a)
3.times { |i| h[:a] << i }

# This is like:
# 3.times { |i| a << i }
# because `h` does not respond to your key :a

h
# => {} 
a
# => [0, 1, 2]

What you want to do, is this:

h = Hash.new { |h, k| h[k] = [] }
3.times { |i| h[:a] << i }

h
# => {:a=>[0, 1, 2]}
Deradon
  • 1,787
  • 12
  • 17