accessing instance variables from an inherited class

A

aidy

Hi,

The below code accesses the value of an instance variable

class Object_References
attr_reader :eek:bj_1, :eek:bj_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
 
S

Stefano Crocco

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 :eek:bj_1, :eek:bj_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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top