Value type or reference type

Hello!

In ruby FAQ, I find the following code.

def addOne(n)
n += 1
end
a = 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?

Thanks in advance.

Sam

“Sam Sungshik Kong” ssk@chol.nospam.net schrieb im Newsbeitrag
news:%2pvc.63994$0L.31478@newssvr29.news.prodigy.com…

Hello!

In ruby FAQ, I find the following code.

def addOne(n)
n += 1
end

This code is misleading. It should read

def addOne(n)
n + 1
end

There is no point in the assignment to n since n is nowhere else used in the
method.

a = 1
addOne(a) # → 2
a # → 1

According to the manual, Fixnum is a value type.
Then the argument ‘a’ must be changed in-place.

No. It would have to be changed in place if Ruby would support call by
reference - which it doesn’t.

Am I misunderstanding?

It seems so. n is not an alias for a but points to the same instance. n +
1 returns a new instance that is assigned to n by having “n += 1”. The
instance pointed to by a is not changed. (Numbers are immutable).

Kind regards

robert