Hello, everyone !!!
I have question about how to use a passing argument. firstly let me
show sample code.
a = 0
def set10(aArg)
aArg = 10
end
set10(a)
p a <--- I wanna get 10 as a result.
How can I do for this one?
Well, Ruby, being a purely object-oriented language, means that
assigning a value to a variable assigns it to a new object (instance)
without affecting the original. So in your example, you just make the
parameter aArg refer to a new number leaving the original untouched.
To alter the data in a parameter, you would have to call a method on
the parameter that changes the data. For example:
----
def method1(string)
string.upcase!
end
s = "hello"
method1(s)
p s # displays "HELLO"
----
Now, some classes have immutable instances -- instances that cannot
have the data within them altered. Fixnum, Bignum, and Float (the
basic numeric types) are all immutable. So that presents a problem.
What you could do is wrap the immutable instance in a mutable class,
as in:
----
require 'delegate'
class Mutable < SimpleDelegator
def initialize(value)
@value = value
super(@value)
end
def reassign(new_value)
@value = new_value
__setobj__(@value)
end
end
def method2(number)
number.reassign(10)
end
n = Mutable.new(3)
method2(n)
p n # displays 10
n = Mutable.new("test")
p n # displays "test"
method2(n)
p n # displays 10
----
I hope that's helpful.
Eric
====
Are you interested in on-site Ruby or Ruby on Rails training
that uses well-designed, real-world, hands-on exercises?
http://LearnRuby.com