From: Tomasz Wegrzanowski Date: 2002-01-05T11:52:49+09:00 Subject: [ruby-talk:30262] Re: self being altered even when .dup'ed On Sat, Jan 05, 2002 at 11:41:08AM +0900, dempsejn@georgetown.edu wrote: > Hey All, > > I've just narrowed down something that was bugging me, and I think I'm > realizing that its a feature, not a bug or error. > I'm extending chomp to take an array. here's the code: > > class Array > def tester > v = self.dup > p self > p v > v[0] = v[0].chomp > v[1].chomp! > p self > p v > end > > end > > If you run that with: > > a = ["str1\n","str2\n"] > a.tester > > you'll see: > > ["str1\n", "str2\n"] > ["str1\n", "str2\n"] > ["str1\n", "str2"] > ["str1", "str2"] > > As I'd expect, the newline is gone from v[0] and v[1], but what bugs me > is that its gone from self[1] as well...its clearly the chomp! call, > but i'm a little confused...i thought .dup would make a copy that i'd > play with leaving the original self alone...it would make sense to me > if i did v = self, but i thought that's where the dupe would solve my > problem...i could code the above slightly differently (using a simple > chomp instead of chomp!) to get around this behavior, but i wanted to > try and understand why its happening... > thanks! > Jack dup makes shallow copy - only array is copied, not it's contents. Array in Ruby contains variables (==pointers), not objects.