From: Jason Creighton Date: 2003-06-14T07:58:34+09:00 Subject: Re: does each work on a copy? On Fri, 13 Jun 2003 10:42:55 +0200 "Robert Klemme" wrote: > > "Jason Creighton" schrieb im > Newsbeitrag > news:20030612123014.33a6449b.androflux@remove.to.reply.softhome.net... > > On Thu, 12 Jun 2003 23:14:37 +0900 > > Rasputin wrote: > > > > > > remember that pretty much everything is a reference and you won't go > far > > > > wrong > > > > > > I thought so, until this happened! > > > The array was full of references, so I thought el held the > > > reference from the Array. > > > > > > It seems to hold a copy of the reference... > > > > No, it doesn't. When you do a: > > Sorry, but in fact you're wrong. The reference is copied indeed. It looked as if the OP thought that 'word' was a "copy" (ie, object.dup), not a reference to the same object in the Array. Sorry, I could have phrased that better. > > a = "Hello world, nice to meet you!".split(' ') > > a.each { |word| word = "lala" } > > p a > > ["Hello", "world,", "nice", "to", "meet", "you!"] > > > > You're binding word to a different object, not changing the objects > themselves. > > Binding "word" to another object is indeed done by copying the reference > to the other object. Or in other terms, after this assignment there is > one more reference to the object. Right: We're not modifing whatever objects were "in" (In the sense that the Array contains references to objects) the Array: We're creating a new object ("lala") and making word refer to that object. Had we done a word.upcase!, that would have modified the object in the array. > a="foo" # one ref to "foo" > b=b # two refs to "foo" > a=nil # one ref to "foo" > b=nil # zero refs to "foo" > > I think you did want to say the right thing but mixed up terms a little. Obviously. :-) > Maybe Perl has contributed to the confusion since it in fact does some > aliasing of references in arrays on function invocations the allow a > function to change array element references directly by simply assigning. > IMHO the ruby way is much cleaner and easier to understand. Once you get used to it: I had used Python before, which basically does the same thing as Ruby, so it wasn't a big shock for me. Jason Creighton