2010-07-09 34 views
0

我有以下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。感谢您的帮助提前。

回答

2

其实原因,不起作用与打印地址无关。它是一行之前:

m = Mp.new这会创建一个新的Mp对象。但是,在Mp的初始化方法中,将创建一个新的Test对象并调用其mytest方法。然后mytest方法再次创建一个新的Mp对象,依此类推。换句话说:Test#mytestMp#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 
+0

我看,怎么那么我会访问字符串=“看”在DEF地址? – rahrahruby 2010-07-09 20:41:18

+0

所以在我的Mp类中,如果我有def地址并且它有='see'我可以通过使用@a访问测试中的一个?你能发表一个简单的例子吗?谢谢 – rahrahruby 2010-07-09 21:05:11

+0

@MAP:不。如果你做'a ='see'',一旦方法返回,你根本不能访问'a'。如果你做'@a ='看'',你可以访问'@ a',但只能在同一个对象内 - 而不能从外部访问。如果在类定义中的方法*和*'attr_accessor:a'中执行'@a ='see'',则可以通过执行'my_mp_object.a'从外部访问'@ a'。我会举一个例子。 – sepp2k 2010-07-09 21:08:39

2

你有一个无限循环。创建Mp类的新对象,这反过来又创造Test类的新对象,然后调用其mytest方法,这反过来又创造Mp类的另一个对象,这反过来又...