[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Suprise in Ruby

Friedrich

11/8/2006 3:44:00 PM

I can not remember having read about it before, however the following
happens here:

irb(main):015:0> arr = Array.new(3, Array.new)
[[], [], []]
irb(main):016:0> arr[0].push(1)
[1]
irb(main):017:0> arr
[[1], [1], [1]]

ruby 1.8.5

but
irb(main):018:0> arr1 = Array.new(3)
[nil, nil, nil]
irb(main):019:0> 0.upto(2) {|i| arr1[i] = Array.new}
0
irb(main):020:0> arr1
[[], [], []]
irb(main):021:0> arr1[0].push(1)
[1]
irb(main):022:0> arr1
[[1], [], []]

I'm not getting it. Is it supposed to work that way?

Regards
Friedrich

--
Please remove just-for-news- to reply via e-mail.
4 Answers

Eric Jacoboni

11/8/2006 4:02:00 PM

0

Friedrich Dominicus <just-for-news-frido@q-software-solutions.de>
writes:


> irb(main):015:0> arr = Array.new(3, Array.new)
> [[], [], []]
> irb(main):016:0> arr[0].push(1)
> [1]
> irb(main):017:0> arr
> [[1], [1], [1]]

> irb(main):018:0> arr1 = Array.new(3)
> [nil, nil, nil]
> irb(main):019:0> 0.upto(2) {|i| arr1[i] = Array.new}
> 0
> irb(main):020:0> arr1
> [[], [], []]
> irb(main):021:0> arr1[0].push(1)
> [1]
> irb(main):022:0> arr1
> [[1], [], []]
>
> I'm not getting it. Is it supposed to work that way?

I think so... see ri Array.new

In your first test, all array items refer to the same
default obj. If it happens to be modified, this modification affects all the
element that refer to this default object.

In you second test, the block create a new copy for each
element. Modifying one of them, doesn't affect the others.


--

Benedikt Heinen

11/8/2006 4:05:00 PM

0

dblack

11/8/2006 4:17:00 PM

0

Friedrich

11/9/2006 3:40:00 AM

0

Benedikt Heinen <ruby@ml.icemark.net> writes:

> On Thu, 9 Nov 2006, Friedrich Dominicus wrote:
>
>> I can not remember having read about it before, however the following
>> happens here:
>>
>> irb(main):015:0> arr = Array.new(3, Array.new)
>
> [...]
>
>> irb(main):018:0> arr1 = Array.new(3)
>> [nil, nil, nil]
>> irb(main):019:0> 0.upto(2) {|i| arr1[i] = Array.new}
>> 0
>
> [...]
>
>> I'm not getting it. Is it supposed to work that way?
>
> Yes. In your first call, 'Array.new' is evaluated ONCE before the call,
> and hence all array members get initialised to use the SAME array.
Yeah it has come to me this night that it's supposed to be right.

Anyway thanks for taking the time to answer

Regards
Friedrich

--
Please remove just-for-news- to reply via e-mail.