`def self.myMethod` 和 `def myMethod` 之间有什么区别吗? [英] Is there any difference between `def self.myMethod` and `def myMethod`?

查看:47
本文介绍了`def self.myMethod` 和 `def myMethod` 之间有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在同时学习 ruby​​ 和 ROR,并注意到其他人代码中的一件事.有时我会看到以这两种明显不同的方式定义方法:

I'm learning ruby and ROR at the same time and noticed one thing in someone else's code. Sometimes I see methods being defined in these two apparently slightly different ways:

class SomeClass < SomeInheritance::Base

  def self.myMethod
  end

  def myOtherMethod
  end

end

有什么区别吗?我的意思是,在方法定义中使用 self 是否会以某种方式影响该方法的工作方式?欢迎任何启示.

Does it make any difference? I mean, does the use of self in a method definition affects the way the method works somehow? Any enlightenment is welcome.

推荐答案

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

def self.method_name will define a class method rather than an instance method - as will

class <<<自己;def foo;结尾;结束

关于该主题的好帖子是这篇文章 来自 Yehuda Katz

A good post on the topic is this post from 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>

这篇关于`def self.myMethod` 和 `def myMethod` 之间有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆