Ruby类问题
问题描述:
我有以下Ruby代码:Ruby类问题
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
这工作得很好,除了在高清部分mytest的地方我试图扑灭m.address。感谢您的帮助提前。
答
其实原因,不起作用与打印地址无关。它是一行之前:
m = Mp.new
这会创建一个新的Mp
对象。但是,在Mp
的初始化方法中,将创建一个新的Test
对象并调用其mytest
方法。然后mytest
方法再次创建一个新的Mp对象,依此类推。换句话说:Test#mytest
和Mp#initialize
是相互和无限递归的。
编辑回应您的评论:
我不太确定我理解这个问题。如果您的意思是“如何访问在address
方法中设置的变量a
,在调用address
后”:您不知道。 a
是一个局部变量,一旦方法返回就会超出范围。如果你想设置一个实例变量,使用@a = 'see'
。 @
表示ruby中的实例变量。如果您希望能够从对象外部访问该变量,请使用attr_accessor :a
来定义@a
的访问器方法。
一个例子:
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
答
你有一个无限循环。创建Mp
类的新对象,这反过来又创造Test
类的新对象,然后调用其mytest
方法,这反过来又创造Mp
类的另一个对象,这反过来又...
我看,怎么那么我会访问字符串=“看”在DEF地址? – rahrahruby 2010-07-09 20:41:18
所以在我的Mp类中,如果我有def地址并且它有='see'我可以通过使用@a访问测试中的一个?你能发表一个简单的例子吗?谢谢 – rahrahruby 2010-07-09 21:05:11
@MAP:不。如果你做'a ='see'',一旦方法返回,你根本不能访问'a'。如果你做'@a ='看'',你可以访问'@ a',但只能在同一个对象内 - 而不能从外部访问。如果在类定义中的方法*和*'attr_accessor:a'中执行'@a ='see'',则可以通过执行'my_mp_object.a'从外部访问'@ a'。我会举一个例子。 – sepp2k 2010-07-09 21:08:39