GreenTriangle
GreenTriangle

Reputation: 2460

Integer variables pass by value, string variables by reference?

Modifications made to b below are also made to a:

a = 'taco'
b = a
b << 's'
a #=> tacos

When I assign a variable x by pointing it at another variable y, x remains a shortcut to y; x and y will be identical. This seems confirmed by the dup method; by saying b = a.dup, b gets a's value at the moment of assignment rather than a shortcut.

But this doesn't happen with integers. When I assign b, it seems to be getting the value of a:

a = 4815
b = a
b /= 2
a #=> 4815

It seems like string variables pass by reference while integer variables pass by value. That doesn't seem right; I know something is wrong in my understanding, but I'm not sure what.

Upvotes: 0

Views: 271

Answers (3)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369556

You need to understand the difference between variables and values. A variable points to a value. Multiple variables can point to the same value.

In Ruby, the only way to modify a variable is via assignment, either simple

foo = :something

or compound assignment

foo ω= :something # for some operator ω
# e.g.
foo += :something
foo <<= :something
foo ||= :something

If you modify a value, that modification will be visible no matter what variable you use to access that value.

Think about it this way: my mum calls me "son", my friends call me "Jörg", my close friends call me "jwm", my band colleagues call me "Jörgislaw", my girlfriend calls me "baby", but no matter what they call me, if I cut my hair, my hair will be gone, regardless of what name they use to refer to me. If, however, my girlfriend assigns a new value to the label "baby", then that does not affect me. (Well … bear with me, it's an analogy :-D )

In Ruby, << typically modifies the receiver, whereas / doesn't.

However, Ruby is always pass-by-value. But the value being passed is a pointer to a value, so that multiple variables can contain multiple copies of the same pointer to the same value.

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122463

That's correct, see Fixnum:

Fixnum objects have immediate value. This means that when they are assigned or passed as parameters, the actual object is passed, rather than a reference to that object.

Assignment does not alias Fixnum objects. There is effectively only one Fixnum object instance for any given integer value, so, for example, you cannot add a singleton method to a Fixnum. Any attempt to add a singleton method to a Fixnum object will raise a TypeError.

Upvotes: 2

sawa
sawa

Reputation: 168209

Irrespective of what you are arguing, b /= 2 is a syntax sugar for b = b / 2. Thus, the new b is b / 2 (or a / 2), which has nothing to do with a.

Upvotes: 2

Related Questions