红宝石类问题

时间:2010-07-09 20:12:20

标签: 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

除了我试图推出m.address的def mytest中的部分之外,这个工作正常。感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

实际上它不起作用的原因与打印地址无关。在此之前是一行:

m = Mp.new这会创建一个新的Mp对象。但是在Mp的initialize方法中,会创建一个新的Test对象并调用其mytest方法。然后mytest方法再次创建一个新的Mp对象,依此类推。换句话说:Test#mytestMp#initialize是相互无限递归的。

根据您的评论进行修改:

我不太确定我理解这个问题。如果您的意思是“如何访问a方法中设置的变量address,则在调用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