Ruby 类继承:什么是“<<"(双小于)? [英] Ruby class inheritance: What is `<<` (double less than)?

查看:32
本文介绍了Ruby 类继承:什么是“<<"(双小于)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class << Awesomeness

这个 <<< 是干什么用的?我搜索了,但结果只告诉我字符串连接...

What is this << for? I searched, but the results only tell me about string concatenation...

推荐答案

虽然 class <<something 是单例类的语法,正如其他人所说,它最常用于在类定义中定义类方法.但这两种用法是一致的.方法如下.

While it's true that class << something is the syntax for a singleton class, as someone else said, it's most often used to define class methods within a class definition. But these two usages are consistent. Here's how.

Ruby 允许您通过执行以下操作向任何特定实例添加方法:

Ruby lets you add methods to any particular instance by doing this:

class << someinstance
  def foo
    "Hello."
  end
end

这将一个方法 foo 添加到某个实例,而不是它的类,而是一个特定的实例.(实际上, foo 被添加到实例的单例类"中,但这或多或少是一个实现怪癖.)执行上述代码后,您可以将方法 foo 发送到某个实例:

This adds a method foo to someinstance, not to its class but to that one particular instance. (Actually, foo is added to the instance's "singleton class," but that's more or less an implementation quirk.) After the above code executes, you can send method foo to someinstance:

someinstance.foo   => "Hello."

但是您不能将 foo 发送到同一类的其他实例.这就是 << 名义上的用途.但是人们更常将此功能用于像这样的句法体操:

but you can't send foo to other instances of the same class. That's what << is nominally for. But people more commonly use this feature for syntactic gymnastics like this:

class Thing
  def do_something
  end

  class << self
    def foo
      puts "I am #{self}"
    end
  end
end

当这段代码——这个类定义——执行时,什么是self?它是 Thing 类.这意味着 class <<self 等同于说将以下方法添加到类 Thing".也就是说, foo 是一个类方法.以上完成后,你可以这样做:

When this code -- this class definition -- executes, what is self? It's the class Thing. Which means class << self is the same as saying "add the following methods to class Thing." That is, foo is a class method. After the above completes, you can do this:

t = Thing.new
t.do_something  => does something
t.class.foo     => "I am Thing"
t.foo           => NoMethodError: undefined method `foo'

当您考虑 << 正在做什么时,这一切都说得通.它是一种附加到特定实例的方式,通常情况下,附加到的实例是一个类,因此块内的方法成为类方法.

And when you think about what << is doing, it all makes sense. It's a way to append to a particular instance, and in the common case, the instance being appended to is a class, so the methods within the block become class methods.

简而言之,这是在类定义块中创建类方法的简洁方法.另一种方法是这样做:

In short, it's a terse way to create class methods within a class definition block. Another way would be to do this:

class Thing
  def self.foo
    # ...
  end
end

同样的事情.您的示例实际上是一个语法错误,但如果您了解 << 如何与实例和 class 关键字一起使用,您就会知道如何纠正它.

Same thing. Your example is actually a syntax error, but if you understand how << is used with instances and the class keyword, you'll know how to correct it.

这篇关于Ruby 类继承:什么是“&lt;&lt;"(双小于)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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