From: Stefan Lang Date: 2005-01-20T00:46:01+09:00 Subject: Re: value by reference Michel Martens wrote: > It's easy to accomplish this task with strings: > > def do_something(a, b, c) > a.replace((a.to_i + 1).to_s) > b.replace((b.to_i + 2).to_s) > c.replace((c.to_i + 3).to_s) > end > > a, b, c = '5', '6', '7' > do_something(a, b, c) > > It would be nice to have a replace method for every object, then we could > write: > > def do_something(a, b, c) > a.replace(a + 1) > b.replace(b + 2) > c.replace(c + 3) > end > > a, b, c = 5, 6, 7 > do_something(a, b, c) But replace doesn't replace the object the variable points to, it just replaces instance variables of the string object: irb(main):001:0> s = "abc" => "abc" irb(main):002:0> s.object_id => 538462462 irb(main):003:0> s.replace "xyz" => "xyz" irb(main):004:0> s => "xyz" irb(main):005:0> s.object_id => 538462462 You can write your replace method if you like: class A attr_reader :ivar def replace(a_obj) @ivar = a_obj.ivar # or generally copy all # instance vars end end def do_something(obj) ... obj.replace(other) end a = A.new do_something(a) p a -- Stefan