From: Peter Date: 2003-12-08T03:48:49+09:00 Subject: Re: newbie question > I am beginning to understand this: > If you assign to the variable within the function the original is NOT > modified. > > if you modify the variable within the function then the original is modified. To me the previous two sentences say exactly the opposite of each other. A variable is local to its scope and cannot be changed outside that scope (except by using closures). But you can change the internal state of the object that the variable points to from anywhere (as long as you're allowed to access that state, of course). > It means if the variable is a simple type like a numeric it cannot be > modified. If I try something like: > v=99 > def f1(n); n=n*n ; end > f1(v) > it will not work. It does what you asked it to do, not what you meant it to do. Actually there's no such thing as a simple type in Ruby (the way I think you mean simple). A numeric is also an object. An integer is special in that you can't change its value (in the sense that you can't change value of 5 to 7), but that's called immutable (at least as far as I know they are immutable). But not all about a numeric is immutable: class Numeric def assoc=(obj) @assoc_obj = obj end def assoc @assoc_obj end end 1.assoc = "This is number one" 2.assoc = "This is number two" print 1.assoc # => This is number one print 2.assoc # => This is number two print (1 + 1).assoc # => This is number two print 3.assoc # => nil But this is changing the internal state of objects, not the variable. After the code above, everywhere in the code, 1.assoc will evaluate to "This is number one" until reassigned, and 2.assoc will evaluate to "This is number two", etc. > Why can't we have something simpler/more explicit like in C or even Perl?. What do you want to make explicit? Everything's an object, and each variable contains a reference to an object, so no need to make that explicit. Maybe you want varargs. Like procedure/function arguments in Pascal that are indicated with var, or pointers to variables like in C and passing those to a function. But Ruby doesn't allow that. If you really need to write a swap method, you can do it like this: def swap(a,b) b,a end x = 1 y = 2 x, y = swap(x, y) Any value that a method returns is explicit this way, not implicit like when you have pointers to variables as in C and pass that to a function to have it place its result there. Peter