I am trying to create an array of certain length, with a default value of
Array.new (such that I will have an array of arrays). I cannot use the
"default" parameter setting Array.new( 4, Array.new ) because I end up with
an array populated with references to the same array. For example:
> a = Array.new( 4, Array.new )
> [ [], [], [], [] ]
> a[0][0] = 1
> a
> [ [1], [1], [1], [1] ]
After some thought, this result was not surprising. The interpreter
evaluates the Array.new parameter before passing, thus it ends up passing a
reference, and this single reference gets populated into each element,
instead of a new array into each.
My next approach was to create the array, with a dafault length, and iterate
over it assigning a new array to each element:
my_arr = Array.new( 4 )
my_arr.each{ |i|
i = Array.new
}
my_arr.each { |j|
puts j.type
}
I get the following output:
NilClass
NilClass
NilClass
NilClass
[nil, nil, nil, nil]
I was finally able to achieve the desired result by using array.each_index:
my_arr.each_index{ |m|
my_arr[m] = Array.new
}
my_arr.each{ |n|
puts n.type
}
Output:
Array
Array
Array
Array
[ [], [], [], [] ]
Conclusion: I understand why I can’t pass Array.new as the default value in
Array.new. However, I do not understand why the first iterative approach
does not work. I obviously know how to acquire the desired result, but that
doesn’t quench my curiousity as to why the other does not work. Can I
bother someone for some enlightenment?
Matt
···
Protect your PC - get McAfee.com VirusScan Online
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963