From: Rasputin Date: 2003-06-14T08:01:40+09:00 Subject: Re: does each work on a copy? * Jason Creighton [030612 19:44]: > 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: > > 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. If you did this: By 'copy of the reference' I meant: ary = %w( a b c d e) ary.each { |r| r = "X" } r is given a copy of the 'reference' (apology for the Perlism), so when you point (ugh, and the Cism) r at "X" you're updating a copy of the reference, not the original reference. Is that about right? And in the below code, string2 = "Hi" is just pointing string2 to a new object, whereas string2[0] = "J" is editing the object through the string2 reference, just as word.upcase! below is doing, as opposed to the |el| el = SPACE in my original post. Sorry for the list noise, think I've got it now. Thanks again for all replies. > a = "Hello world, nice to meet you!".split(' ') > a.each { |word| word.upcase! } > p a > ["HELLO", "WORLD,", "NICE", "TO", "MEET", "YOU!"] > > It's the same thing that happens when you do this: > > string1 = "Hello, world!" > string2 = string1 > string2 = "Hi!" > p string1 > "Hello, world!" > > You haven't changed the object that string1 points to: You've made a new string object ("Hi!") and bind string2 to that. If you did a: > > string1 = "Hello, world!" > string2 = string1 > string2[0] = "J" > p string1 > "Jello, world!" > > Here you call the []= method of the object that string2 points to,(no rebinding of string2) which means that string1 and string2 still point to the same object. > > Jason Creighton > -- Rasputin :: Jack of All Trades - Master of Nuns