ruby类方法定义的问题

时间:2013-04-28 09:47:22

标签: ruby

以下代码返回错误:

class ABC
  def self.method1()
    method2
  end

  def method2
  end
end
  

ABC.method1

     

NameError:未定义的局部变量或ABC的方法`method2':Class

但是,下面的代码运行正常:

class ABC
  def initialize
    method2
  end

  def method2
  end
end
  

ABC.new

是否需要使用initialize才能正确定义类中的所有方法?第一个代码块出了什么问题?

3 个答案:

答案 0 :(得分:3)

如果没有该类的对象,则无法调用实例方法。

method1是类ABC的类方法,因此您可以在类本身上调用它。但是如果你想调用你的实例方法method2,你需要一个类ABC的对象,而不是在类本身上调用它,即。

o = ABC.new
o.method2

其他代码有效,因为在initialize中,您已经拥有ABC的实例,您的方法调用可以理解为self.method2

答案 1 :(得分:2)

method1是静态的,method2不是。

ABC.method2未定义,ABC.new.method2没问题

class ABC

  def self.method1()
    method2    # ABC.method2
  end

  def initialize
    method2    # self.method2, self is instance of ABC
  end

  def method2
  end
end

答案 2 :(得分:0)

在第一个代码块中,您尝试在类方法中调用实例方法,就像您调用ABC.method2,但ABC没有这样的方法。

相关问题