On Sun, Jan 17, 2010 at 7:00 PM, lalawawa [email protected] wrote:
=> 7
irb(main):006:0> b
=> 5
irb(main):007:0>
They are actually pass by reference, as in Java and C++, or arrays in C.
For example
def woof(a)
a << “e”
end
a = “bcd”
woof(a)
a # => “bcde”
Your example does not reflect this, because of two issues.
The first is that numbers are immutable, so even though you can modify
the
objects themselves, you can’t modify numbers.
The second is that += does not modify the object itself, it modifies the
label. It is the same as saying a=a+1
This is because of the first reason, since they are immutable you must
do
a=a+1 instead of a++
On Sun, Jan 17, 2010 at 7:00 PM, lalawawa [email protected] wrote:
would output 7.
Honestly, I don’t ever really find myself in situations where I need to
do
this, you may need to rethink your approach.
Regardless, I suppose I can think of three alternatives.
Alternative 1 is to use an instance variable, don’t do this trivially,
they
will pollute your namespace.
def woof
@a+=2
end
@a = 2
woof
@a # => 4
Alternative 2 is to have the method return the new value ie, it seems a
little messy, though, since it requires code outside to know that it
needs
to assign results in some given manner.
def woof(a)
a+2
end
a = 2
a = woof(a)
a # => 4
Alternative 3 is to wrap the variable in a mutable object, like Java’s
Integer (except that isn’t mutable either :P), but I can’t seem to come
up
with a way of doing this that I don’t hate.
If you care to show your example, we might be able to spot a more Ruby
approach.