Gavri Savio Fernandez [mailto:Gavri_F@infosys.com]:
Sam Sungshik Kong [mailto:ssk@chol.nospam.net]:
Hello!
In ruby FAQ, I find the following code.
def addOne(n)
n += 1
enda = 1
addOne(a) # → 2
a # → 1
According to the manual, Fixnum is a value type. Then the
argument ‘a’ must be changed in-place.Am I misunderstanding?
Yes. ‘n’ is a label, not a memory slot, and ‘+=’ is syntax sugar.
Effectively, your addOne(n) definition is actually:
def add_one(n)
n = n + 1
end
All objects are passed by reference – even value types (Fixnum,
Symbol) are treated from the Ruby programmer’s point of view as
being passed by reference. Compare:
def add_ones(n)
n += “1”
end
a = “0”
add_ones(a) # => “01”
a # => “0”
This is because ‘n’ is replaced with a new object; the old object is
not modified. This can be visibly seen with:
def add_one(n)
puts n.id
n += 1
puts n.id
end
a = 0; puts a.id; add_one(a); puts a.id
This will do what you want on a String:
def add_ones(n)
n << “1”
end
There is nothing that will do what you want for a Fixnum, because it
is an immediate and immutable value.
Fixnum is value type, but whatever you pass into addOne() is
passed by value, which means that a copy of the value is made.
This is not so: everything [except immediate values] in Ruby is
passed by reference, not by value. Immediate values are immutable in
any case, so it is as if they were passed by reference in any case.
There is no meaningful distinction between a “reference type” and a
“value type” from the Ruby programmer’s perspective.
The trick is that variables aren’t bound to objects the way that
they are in languages like C++ and Java; they merely refer to a
given object reference at a given time.
-austin
···
–
austin ziegler * austin.ziegler@evault.com