Actually the reason it doesn't work has nothing to do with printing the address. It's one line before that:
m = Mp.new
this creates a new Mp
object. However inside Mp
's initialize method a new Test
object is created and its mytest
method is called. The mytest
method then again creates a new Mp object and so on. In other words: Test#mytest
and Mp#initialize
are 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 a
which was set in the address
method, after address
has been called": you don't. a
is 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, use attr_accessor :a
to define accessor methods for @a
.
An example:
class Mp
attr_accessor :c
def initialize
initialize_variables
puts @c
puts @b # I can access @c and @b here because it's an instance variable
# and I'm within the same object
# puts a # This does not work because a is a local variable from the
# initialize_variables method and no longer in scope
end
def initialize_variables
a = "a"
@b = "b"
@c = "c"
puts a # I can access a here because I'm still inside the method
# where a was defined
end
end
m = Mp.new
# puts m.a
# puts m.b # These don't work because there are no methods a or b
puts m.c # This works because attr_accessor defined a method c which
# returns the content of m's @c variable