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

mar*_*cio 6 ruby ruby-on-rails

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

class SomeClass < SomeInheritance::Base

  def self.myMethod
  end

  def myOtherMethod
  end

end
Run Code Online (Sandbox Code Playgroud)

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

klo*_*ner 21

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

class << self; def foo; end; end

关于这个主题的好帖子是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
 => #<Foo:0x10dfe3a40> 

> f.method_1
 => "called from instance"  

> f.method_2
NoMethodError: undefined method 'method_2' for #<Foo:0x10dfe3a40>

> f.method_3
NoMethodError: undefined method 'method_3' for #<Foo:0x10dfe3a40>
Run Code Online (Sandbox Code Playgroud)

  • +1很好的答案:一个例子值得1000字的解释. (2认同)