[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

accessing instance variables from an inherited class

aidy

11/16/2007 5:43:00 PM

Hi,

The below code accesses the value of an instance variable

class Object_References
attr_reader :obj_1, :obj_2

def initialize
@obj_1 = "Object_1"
@obj_2 = "Object_2"
end

end

ref = Object_References.new
puts ref.obj_1
puts ref.obj_2

But how can I access the same value in a subclass?

class Whatever < Object_References

#how can I access the above objects variables here

end

Thanks

Aidy
1 Answer

Stefano Crocco

11/16/2007 5:53:00 PM

0

Alle venerd=EC 16 novembre 2007, aidy ha scritto:
> Hi,
>
> The below code accesses the value of an instance variable
>
> class Object_References
> attr_reader :obj_1, :obj_2
>
> def initialize
> @obj_1 =3D "Object_1"
> @obj_2 =3D "Object_2"
> end
>
> end
>
> ref =3D Object_References.new
> puts ref.obj_1
> puts ref.obj_2
>
> But how can I access the same value in a subclass?
>
> class Whatever < Object_References
>
> #how can I access the above objects variables here
>
> end
>
> Thanks
>
> Aidy

You can access them as you would in the base class:

class A

def initialize
@x =3D 2
end

end

class B < A
=20
def puts_x
puts @x
end

def x=3D(value)
@x =3D value
end

end

b =3D B.new
b.puts_x
b.x=3D3
b.puts_x

Output:
2
3

I hope this helps

Stefano