在 ruby​​ 中,self.method 和类中的方法有什么区别 <<自己 [英] in ruby what's the difference between self.method and a method within class << self

查看:34
本文介绍了在 ruby​​ 中,self.method 和类中的方法有什么区别 <<自己的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Foo

  def self.one; 1 end

  class << self
    def two; 2 end
  end

end
puts Foo.singleton_methods.inspect # => ["two", "one"]

我被告知上述方法一"和二"在概念上是不同的,但我不知道如何.它们都是单例方法 - 在概念和应用上有什么区别?

I've been told the above methods "one" and "two" are conceptually different but I don't see how. They are both singleton methods - what's the difference in concept and also application?

推荐答案

在应用上,没有区别.在概念上,区别是微妙的,但在第一种情况下,您是在当前上下文中操作,并在另一个类实例上定义方法(实际上是其 Eigen 类中的实例方法),而在第二种情况下,您正在输入其他类实例的元类(Eigenclass")的上下文,然后定义一个实例方法.

In application, there is no difference. In concept, the difference is subtle, but in the first case, you are operating in the current context, and defining a method on another class instance (actually, an instance method in its Eigenclass), whereas in the second case, you are entering the context of the the metaclass ("Eigenclass") of other class instance, and then defining an instance method.

我应该补充一点,选择 类的原因 <<self 在某些情况下是...

I should add that the reasons for choosing the class << self in some cases are...

  1. 定义多个类方法时的语法更简洁.
  2. 除了 def my_method ... 之外,您还可以在 Eigenclass 上下文中执行其他类型的代码.例如,您可以在该代码块中说 attr_accessor :some_attribute.
  1. Cleaner syntax when defining more than a few class-methods.
  2. You can execute other kinds of code in the Eigenclass context besides just def my_method .... You can, for instance, say attr_accessor :some_attribute in that block of code.

这篇关于在 ruby​​ 中,self.method 和类中的方法有什么区别 &lt;&lt;自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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