From: Austin Ziegler Date: 2003-12-07T23:37:01+09:00 Subject: Re: newbie question On Sun, 7 Dec 2003 14:43:58 +0900, nainar wrote: > On Thu, Dec 04, 2003 at 07:24:28PM +0900, Peter wrote: >> [snip] >>> To swap two numbers x and y, call >>> def swap(x,y) >>> z = x >>> x = y >>> y = z >>> end >> This won't work in Ruby. If you call swap(a[i], a[j]), two >> variables x and y are created, and the values of a[i] and a[j] >> are copied to it. Executing the body effectively interchanges the >> values of x and y, but not those of a[i] and a[j]. Consider >> replacing a call to swap with a simple > If function are params are only copies, why do the two functions > below behave differently: Function params aren't copies; they are (1) variables that (2) contain references to objects. Remember that in Ruby, variables are just tags that refer to objects. They aren't memory slots in and of themselves like they are in other languages. > def f1(a) > a=[9,8,7] > end In this case, it's helpful to decorate this a bit differently: def f1(a) p a a = [9, 8, 7] p a a end When you run that version of f1, you'll notice that the object IDs are different. > def f2(b) > b[0]=[9,8,7] > end Again, decorated differently: def f2(b) p b b[0] = [9, 8, 7] p b b end In this case, you'll notice that the object IDs are the same. This is becasue you're not calling straight assignment in this case. You're calling b's []= method, just as if you had done: b.__send__(:[]=, 0, [9, 8, 7]) Hopefully it makes more sense now. -austin -- austin ziegler * austin@halostatue.ca * Toronto, ON, Canada software designer * pragmatic programmer * 2003.12.07 * 09.29.05