From: Robert Klemme Date: 2003-06-12T23:22:26+09:00 Subject: Re: does each work on a copy? "Rasputin" schrieb im Newsbeitrag news:20030612134643.GA76491@shrike.private.submonkey.net... > > This has me confused (It's getting to be a frequent experience). > > ----------------8<---------------- > > SPACE = 1 > > a = Array.new(5) > b = Array.new(5, SPACE) > > a.each { |el| > el = SPACE > } > > puts "a = #{a.join("-")}" > puts "b = #{b.join("-")}" > > ----------------8<---------------- > > I'd expect to have a first output line similar to the second,but I get: > > rasputin@shrike rasputin$ ruby /tmp/q > a = ---- > b = 1-1-1-1-1 > rasputin@shrike rasputin$ > > Now, is this because each is returning a copy of the element? > It's the most plausible explanation > (because if I replace a.each with a.collect! it works as I expected) > but if so I'm surprised it hasn't bitten me on the ass before. > > I know the Array is full of nils, but can't see why that would > cause what I'n seeing. > > Please hit me wirh a clue bat. Thanks. Clue bat: your block assigns to a local variable "e", which does not change the array. You can assign as much as you like to "e", it does not have any effect on "a". If you want to modify the array use a.map! or a.collect! instead of a.each: irb(main):001:0> SPACE = 1 1 irb(main):002:0> irb(main):003:0* a = Array.new(5) [nil, nil, nil, nil, nil] irb(main):004:0> b = Array.new(5, SPACE) [1, 1, 1, 1, 1] irb(main):005:0> irb(main):006:0* a.map! { SPACE } [1, 1, 1, 1, 1] irb(main):007:0> irb(main):008:0* irb(main):009:0* puts "a = #{a.join("-")}" a = 1-1-1-1-1 nil irb(main):010:0> puts "b = #{b.join("-")}" b = 1-1-1-1-1 nil irb(main):011:0> Cheers robert