In message "[ruby-talk:12130] Weird Array behavior"
on 01/03/06, jjthrash / pobox.com <jjthrash / pobox.com> writes:
>array = [[12345, "val"],[23456, "val2"],[34567, "val3"],[45678,"val4"]]
>oldArray = array
>array = Array.new((oldArray.size.to_f/3).ceil, Array.new(2))
>oldArray.each_with_index do |entry, index|
> if array[(index.to_f/3).floor][0] == nil
> array[(index.to_f/3).floor][0] = entry[0]
> #INSPECTION POINT
>If I debug and step up to the first time I reach the INSPECTION
>POINT, I expect the value array to be
>[[12345, nil], [nil, nil]], but it's actually
>[[12345, nil], [12345, nil]]
Array.new fills always with an *identical* object, specified as the
2nd argument. So we have to fill *after* create an array.
Each of the following create empty an array consists of empty arrays:
#1 straightforward
array = []
(oldArray.size.to_f/3).ceil.times{ array.push Array.new(2) }
#2 intuitive
array = Array.new((oldArray.size.to_f/3).ceil).map{Array.new(2)}
#3 faster than the above
(array = Array.new((oldArray.size.to_f/3).ceil)).map!{Array.new(2)}
-- Gotoken