Robinson Risquez wrote in post #1062083:
Certainly can be done in many ways, but what I want to do is spend just
an attribute as a parameter to a method of the form: object.attribute,
then you can modify this attribute in the method, as follows:
def adder (attribute)
attribute + = 1
end
No, you cannot do it that way.
First of all, Ruby doesn't have attributes in the sense of classical
object oriented languages like Java or C++. When you write
"object.attribute", you're actually calling a getter method:
object.attributes(). It is *not* a variable, even though the missing
parantheses make it look like it (which is intended).
Secondly: Even *if* Ruby had classical object attributes, your code
wouldn't work. When you call a method and use a variable as an argument,
then the *content* of the variable will be passed to the method, not the
variable itself.
For example:
···
#---------------
def my_method(arg)
p arg
end
my_var = 1
my_method(my_var)
#---------------
This will pass the Integer 1 to my_method. The variable itself is *not*
passed, so you cannot reassign it in the method.
What you can do is to pass an object and the name of an attribute and
then let the method call the correspoding setter method:
#---------------
class A
attr_accessor :x
def initialize
@x = 0
end
end
def addr(object, attribute_name)
# call the getter method
current_value = object.public_send(attribute_name)
# call the setter method
object.public_send("#{attribute_name}=", current_value + 1)
end
a = A.new()
puts a.x
addr(a, :x)
puts a.x
#---------------
However, I don't find this a very good programming style.
--
Posted via http://www.ruby-forum.com/\.