From: Saji Hameed Date: 2012-05-25T12:27:27+09:00 Subject: Re: Modify an attribute in a method? --f46d0401fd9d6ec74604c0d3f2f7 Content-Type: text/plain; charset=UTF-8 On Fri, May 25, 2012 at 12:14 PM, Robinson Risquez wrote: > > 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 > > That's what I do, but can not find the way. > then may be this is better .... class SomeClass attr_accessor :attribute def initialize(attribute) @attribute = attribute end def adder(attribute) self.attribute += 1 end end val = SomeClass.new(5) k=0 while (k<10) do puts val.adder(:attribute) k+=1 end without the 'self', ruby interprets "attribute" to be a local variable! saji -- Saji N Hameed, ARC-ENV, Center for Advanced Information Science and Technology, University of Aizu, Tsuruga, Ikki-machi, Aizuwakamatsu-shi, Fukushima 965-8580, Japan Tel: +81242 37-2736 Fax:+81242 37-2760 email: saji@u-aizu.ac.jp url: http://www.u-aizu.ac.jp bib: http://www.researcherid.com/rid/B-9188-2009 --f46d0401fd9d6ec74604c0d3f2f7 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable

On Fri, May 25, 2012 at 12:14 PM, Robins= on Risquez <lists@ruby-forum.com> wrote:

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:

=C2=A0def adder (attribute)
=C2=A0 attribute + =3D 1
=C2=A0end

=C2=A0That's what I do, but can not find the way.

then may b= e this is better ....
=C2=A0
class SomeClass
=C2=A0 at= tr_accessor :attribute

=C2=A0 def initialize(attribute)
=C2=A0=C2=A0=C2=A0 @attribute =3D a= ttribute
=C2=A0 end

=C2=A0 def adder(attribute)
=C2=A0=C2=A0= =C2=A0 self.attribute +=3D 1
=C2=A0 end
end

val =3D SomeClass.= new(5)

k=3D0
while (k<10) do
=C2=A0 puts val.adder(:attribu= te)
=C2=A0 k+=3D1
end

=C2=A0 without the 'self', ruby interpr= ets "attribute" to be a local variable!

saji =C2=A0=C2=A0= =C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2= =A0=C2=A0=C2=A0=C2=A0

--

Saji N Hameed,
AR= C-ENV, Center for Advanced Information Science and Technology,
University of Aizu, Tsuruga, Ikki-machi,
Aizuwakamatsu-shi, Fukushima 96= 5-8580,
Japan
=C2=A0 =C2=A0 =C2=A0 =C2=A0
Tel: +81242 37-2736
= Fax:+81242 37-2760
=C2=A0email: saji@u-aizu.ac.jp
=C2=A0url: http://www= .u-aizu.ac.jp
=C2=A0bib: http://www.researcherid.com/rid/B-9188-2009<= /a>
--f46d0401fd9d6ec74604c0d3f2f7--