accessing instance variables from an inherited class

Discussion in 'Ruby' started by aidy, Nov 16, 2007.

  1. aidy

    aidy Guest

    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
     
    aidy, Nov 16, 2007
    #1
    1. Advertising

  2. 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
     
    Stefano Crocco, Nov 16, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    10
    Views:
    35,906
    jporter892
    Jun 6, 2011
  2. Alicia
    Replies:
    3
    Views:
    954
    jjr2004a
    Nov 24, 2004
  3. mrstephengross
    Replies:
    4
    Views:
    466
    Diez B. Roggisch
    Feb 27, 2008
  4. David Garamond
    Replies:
    5
    Views:
    250
    Ara.T.Howard
    Jun 8, 2004
  5. 7stud --
    Replies:
    11
    Views:
    411
    7stud --
    Nov 9, 2007
Loading...

Share This Page