I have the following ruby code:
class Mp
def initialize
Test.new.mytest
Work.new.mywork
ha
address
end
def ha
puts "message from ha"
end
def address
a='see'
end
end
class Test
def mytest
m=Mp.new
puts "Message from test do you #{m.address}"
end
end
class Work
def mywork
puts "message from work"
end
end
Mp.new
This works fine except the part in def mytest where I’m trying to put out the m.address. Thanks for your help in advance.
Actually the reason it doesn’t work has nothing to do with printing the address. It’s one line before that:
m = Mp.newthis creates a newMpobject. However insideMp‘s initialize method a newTestobject is created and itsmytestmethod is called. Themytestmethod then again creates a new Mp object and so on. In other words:Test#mytestandMp#initializeare mutually and infinitely recursive.Edit in response to your comment:
I’m not quite sure I understood the question. If you mean “How do I access the variable
awhich was set in theaddressmethod, afteraddresshas been called”: you don’t.ais a local variable that goes out of scope once the method has returned. If you want to set an instance variable use@a = 'see'.@denotes instance variables in ruby. If you want to be able to access that variable from outside the object, useattr_accessor :ato define accessor methods for@a.An example: