Todd Benson
9/19/2008 6:33:00 PM
On Fri, Sep 19, 2008 at 12:40 PM, Glenn <glenn_ritz@yahoo.com> wrote:
> Hi,
>
> Can anyone explain why hash_of_indexes1 in the code below works, but hash_of_index2 doesn't? (I got the first method as a response to a previous post.)
snip
> class Array
> def hash_of_indexes1
> h = Hash.new
> each_with_index { |e, i| h[e.to_f] = Array( h[e.to_f] ) << i }
> h
> end
>
> def hash_of_indexes2
> h = Hash.new([])
> each_with_index { |e, i| h[e.to_f] = h[e.to_f] << i }
> h
> end
> end
>
> [1, 2, 2, 3].hash_of_indexes1.inspect ## --> returns {1.0=>[0], 3.0=>[3], 2.0=>[1, 2]}
>
> [1, 2, 2, 3].hash_of_indexes2.inspect ## --> returns {1.0=>[0, 1, 2, 3], 3.0=>[0, 1, 2, 3], 2.0=>[0, 1, 2, 3]}
With hash_of_indexes2, the array assigned to the each hash key is the
same Array object. You can tell this by comparing their __id__ tags
(apologies for lazy style)...
a = 1,2,3,4
b = 1,2,3,4
a == b
=> true
a.__id__ == b.__id__
=> true
a = Array([1,2,3,4])
b = Array([1,2,3,4])
a == b
=> true
a.__id__ == b.__id__
=> false
Todd