From: Todd Benson Date: 2007-07-26T04:33:08+09:00 Subject: Re: Question - Passing parameters by reference On 7/25/07, caof2005 wrote: > Thanks for the response, although I was just wondering that using > Strings as a parameters in a method definition is a special case. > Let me explain.... > I observed that when you use a string as a parameter in a method > definition, it can be changed by applying several operations inside > the method, for instance you can change it, by adding letters to the > string, changing the content to uppercase etc. > So I figured out that when you use a string, what really happens > inside the method is that you don't create a new object, you just use > the reference. > In opposition as if you use other kind of parameters in a method > definition, let say for example an int variable. > If you try to change this int variable inside the method, it > simply doesn't work, what happens is that you get a "copy" of the > object that you're passing but after the method is finished, that > copy disappears and at the end the parameter that you passed was not > affected. > Am I correct with my conclusions? > > Regards > Carlos Yes, because a Fixnum object is immutable. Also, like David said, you cannot change bindings. See... irb> def f x; x = 6; end => nil irb> a = 1 => 1 irb> f a => 6 irb> a => 1 Now look at something that is mutable, like String... irb> a = "hello" => "hello" irb> def g x; x << "bye"; end => nil irb> f a "hellobye" irb> a "hellobye" But watch this assignment... irb> a = "hello" => "hello" irb> a.__id__ => 68099810 irb> def g x irb> puts x.__id__ irb> x = "bye" #here is an attempt at assignment irb> puts x.__id__ #oops, not correct scope, created new string object with name x irb> end => nil irb> g a 68099810 68052050 => nil irb> a #should be unchanged => "hello" So yes, mutable objects you can change within method scope, but not reassign. To answer Chris's question about what you should do when you are already returning something, well, you can return more than one thing. You can also send an object as a parameter (Array, Hash, whatever), which of course can be modified within the method. cheers, Todd