From: Jeremy Walker Date: 2012-05-14T21:16:35+09:00 Subject: Re: Accessing child variables --f46d043745018f680b04bffe0edf Content-Type: text/plain; charset=ISO-8859-1 On 14 May 2012 12:50, Stuart Morrison wrote: > Hi > > I am learning ruby and I am trying to access variables from a child > object. Can anyone help me access the following variable please? > > class A > attr_accessor :valA > end > > class B > attr_accessor :myarray > > def initialize > @myarray = [] > end > > def myarray > @myarray = myarray > end > end #end Class > > class My_top > > attr_accessor :c > > c = B.new > > objA = A.new > > objA.valA = 10 > > c.myarray << objA > > end > > my_top = My_top.new > puts my_top.c.myarray.inspect > > > My error is as follows: > > stack level too deep (SystemStackError) > This is a hint to you that a method you are calling is calling itself. If you look at your implementation of myarray, you have "@myarray = myarray". This means that when you call myarray, it's calling itself over and over again. This is recursion and in this situation, this is bad. At the top of your class you have "attr_accessor :myarray" That in effect defines the following two methods: def myarray return @myarray end def myarray=(arr) @myarray = arr end Your method of "myarray" is overriding the default one and causing the problem. Try removing it and see if that fixes it. Jeremy Walker > > -- > Posted via http://www.ruby-forum.com/. > > --f46d043745018f680b04bffe0edf Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable

On 14 May 2012 12:50, Stuart Morrison <lists@ruby-forum.com> wrote:
Hi

I am learning ruby and I am trying to access variables from a child
object. =A0Can anyone help me access the following variable please?

=A0class A
=A0 =A0 attr_accessor :valA
=A0end

=A0class B
=A0 =A0attr_accessor :myarray

=A0 =A0def initialize
=A0 =A0 =A0@myarray =3D []
=A0 =A0end

=A0 =A0def myarray
=A0 =A0 =A0@myarray =3D myarray
=A0 =A0end
=A0end #end Class

=A0class My_top

=A0 =A0attr_accessor :c

=A0 =A0c =3D B.new

=A0 =A0objA =3D A.new

=A0 =A0objA.valA =3D 10

=A0 =A0c.myarray << objA

end

=A0my_top =3D My_top.new
=A0puts my_top.c.myarray.inspect


My error is as follows:

stack level too deep (SystemStackError)

This is a hint to you that a method you are calling is calling itself.

If you look at your implementation of=A0myarray, you = have "@myarray =3D myarray". This means that when you call myarra= y, it's calling itself over and over again. This is recursion and in th= is situation, this is bad.

At the top of your class you have "attr_accessor := myarray"

That in effect defines the following= two methods:=A0
def myarray
=A0 return @myarray
end

def myarray=3D(arr)
=A0 @myarray =3D= arr
end

Your method of "myarray&qu= ot; is overriding the default one and causing the problem. Try removing it = and see if that fixes it.

Jeremy Walker
=A0

--
Posted via http://= www.ruby-forum.com/.


--f46d043745018f680b04bffe0edf--