`def self.myMethod`和`def myMethod`之间有什么区别吗?

我正在学习ruby和ROR,同时注意到别人的代码中有一件事。 有时我看到这两种方法的定义略有不同:

class SomeClass < SomeInheritance::Base def self.myMethod end def myOtherMethod end end 

这有什么不同吗? 我的意思是,在方法定义中使用self会影响方法以某种方式工作的方式吗? 任何启蒙都是受欢迎的。

def self.method_name将定义一个类方法而不是一个实例方法 – 就像那样

class << self; def foo; end; end

关于这个主题的好post是Yehuda Katz的这篇文章

例如:

 class Foo def method_1 "called from instance" end def self.method_2 "called from class" end class << self def method_3 "also called from class" end end end > Foo.method_1 NoMethodError: undefined method 'method_1' for Foo:Class > Foo.method_2 => "called from class" > Foo.method_3 => "also called from class" > f = Foo.new => # > f.method_1 => "called from instance" > f.method_2 NoMethodError: undefined method 'method_2' for # > f.method_3 NoMethodError: undefined method 'method_3' for # 

如果您尝试此代码:

 class SomeClass p self end 

你会得到’SomeClass’印刷品。 那是因为self引用了SomeClass对象(是的,clases也是Ruby中的对象)。

使用self,您可以定义class_method,即类对象上的方法 (尽管它实际上是在对象的元类中定义的……):

 class SomeClass def self.class_method puts "I'm a class method" end def instance_method puts "I'm an instance method" end end SomeClass.class_method # I'm a class method 

关于Ruby对象模型还有很多要了解的内容。 戴夫托马斯就这个问题发表了精彩的演讲 – 请看@ Octopus-Paul给你推荐的链接。