本文介绍了为什么不能在 Symbols 或 Fixnums 上定义单例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些 Ruby 类不允许在其实例上定义单例方法.例如,Symbol:

There are a some Ruby classes that don't allow singleton methods to be defined on their instances. For example, Symbol:

var = :asymbol

def var.hello
  "hello"
end

# TypeError: can't define singleton method "hello" for Symbol

我认为这可能是对所有直接值的限制,但它似乎适用于 niltruefalse>(但不是 FixnumBignum 的实例):

I thought this might be a restriction on all immediate values, but it seems to work for nil, true, and false (but not instances of Fixnum or Bignum):

var = true

def var.hello
  "hello"
end

var.hello #=> "hello"

我不明白为什么 Ruby 允许在某些类的对象上定义单例方法,而不允许在其他类上定义.

I don't understand why why Ruby allows singleton methods to be defined on certain classes of objects but not others.

推荐答案

这与 此处 来自 Matz.

This has to do with a concept called 'immediate values' as described here by Matz.

事实上,没有立即值应该允许单例方法.但是,在 truefalsenil 的情况下,实际上有支持这些值的单例类(或者值实际上是单例类 - 我不确定).因此,您可以将单例实例添加到后备类,该类表现为值本身.Numeric 和 Symbol 实例不是单例(显然)并且无处保存单例方法.

In truth, no immediate values should permit a singleton method. However, in the case of true, false, and nil, there are actually singleton classes that back these values (or the value is actually the singleton class - I'm not sure about this). You can therefore add singleton instances to the backing class which manifests as though it were the value itself. Numeric and Symbol instances are not singletons (obviously) and have nowhere to hold singleton methods.

这篇关于为什么不能在 Symbols 或 Fixnums 上定义单例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 09:01