From: Austin Ziegler Date: 2005-01-20T02:05:51+09:00 Subject: Re: value by reference On Thu, 20 Jan 2005 01:10:22 +0900, Mohammad Khan wrote: > def do_something(a, b, c) > a += 1 > b += 2 > c += 3 > end > > def another_do_something(foo = Foo.new) > foo.do_something > end > > class Foo > def initialize > @value = 0 > end > > def value > return @value > end > > def value=(val) > @value = val > end > > def do_something > @value += 1 > @value += 2 > @value += 3 > end > end > a, b, c = 5, 6, 7 > f = Foo.new [...] > If everything is object, Why can't I do > do_something(a.clone, b.clone, c.clone) # I don't want them to > # be changed > do_something(a, b, c) # change a, b, c like > # other objects > Hope, I could explain properly what I am trying to understand. I don't know why you're not getting this, as it is very simple. a, b, and c are not objects. They're variables. When you call Foo#do_something, you're changing the internal state of an object. When you call Object#do_something, you're passing three variables that can refer to just about any object. It's no different than if I defined do_something as: def do_something(a, b, c) a += Foo.new b += Foo.new c += Foo.new end As long as Foo can be added to the values of a, b, and c, I'm going to get three completely new objects. Try it with this: def do_something(a, b, c) a += "-half" b += "-thirds" c += "-fourths" puts a.id, b.id, c.id [ a, b, c ] end def do_something2(a, b, c) a << "-half" b << "-thirds" c << "-fourths" puts a.id, b.id, c.id [ a, b, c ] end a = "one" b = "two" c = "three" puts "#{a}<#{a.id}>, #{b}<#{b.id}>, #{c}<#{c.id}>" x, y, z = do_something(a, b, c) puts "#{x}<#{x.id}>, #{y}<#{y.id}>, #{z}<#{z.id}>" puts "#{a}<#{a.id}>, #{b}<#{b.id}>, #{c}<#{c.id}>" x, y, z = do_something2(a, b, c) puts "#{a}<#{a.id}>, #{b}<#{b.id}>, #{c}<#{c.id}>" puts "#{x}<#{x.id}>, #{y}<#{y.id}>, #{z}<#{z.id}>" This will help you understand. #<< modifies a String in-place. It's concatenation. += concatenates and creates a new string. -austin -- Austin Ziegler * halostatue@gmail.com * Alternate: austin@halostatue.ca