Value type or reference type

  • Thread starter Sam Sungshik Kong
  • Start date
S

Sam Sungshik Kong

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
 
R

Robert Klemme

Sam Sungshik Kong said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top