Bug #2006: Setting Hash default to an array hides the hash keys
http://redmine.ruby-lang.org/issues/show/2006

Author: Alan Stebbens
Status: Open, Priority: Normal
ruby -v: ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin9.5.0]

Setting the default value of a hash to an array causes the keys and values methods results to be empty.

It may be counter-intuitive and not actually useful, but the assignment of the default value to an array causes all values to be _same_ array object.

So, the little sums and subtractions end up applying to the same array object, no matter what the hash key is.

However, even though the hash keys and values appear to be empty, they are clearly still there.

% cat bug1.rb
#!/usr/bin/env ruby

h = Hash.new [0, 0]
d = ['a', 'b', 'c']
puts h

d.each_with_index{|k,x|
  h[k][0] += x
  h[k][1] -= x
}

puts "h.inspect = #{h.inspect}"
puts "h.keys    = #{h.keys.inspect}"
puts "h.values  = #{h.values.inspect}"

d.each{|k| puts "#{k} = #{h[k].inspect}"}

----

$ ruby bug1.rb 

h.inspect = {}
h.keys    = []
h.values  = []
a = [3, -3]
b = [3, -3]
c = [3, -3]


----------------------------------------
http://redmine.ruby-lang.org