self being altered even when .dup'ed 
Author Message
 self being altered even when .dup'ed

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



Wed, 23 Jun 2004 10:47:02 GMT  
 self being altered even when .dup'ed

Quote:

> 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.


Wed, 23 Jun 2004 10:57:38 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. MSSQL 'alter table' from Clarion

2. Altering 'print'/mod_python

3. segfault dup'ing string through C++ (via swig) module

4. Using TclX's dup with Expect

5. We've been /.'ed!

6. Accessing 'DIM'ed group variables

7. Q: how to get pid of 'start'ed process (WNT, os.system)

8. A problem - can itbe 'prolog'ed?

9. un'expect'ed eof

10. ISO: sample code to dynamically alter Tk's widget label language

11. Making the attribute 'self' preferred

12. need info on 'SELF'

 

 
Powered by phpBB® Forum Software