NilClass、TrueClass 和 FalseClass 的目的是什么
NilClass
、TrueClass
和 FalseClass
各有一个实例,即 nil
、true
和false
,这些都是常量,拥有这些类的目的是什么?为什么它们不能是 Object
类的实例,并且所有相关方法都可以简单地定义为 nil
、true
和 上的单例方法假的?一个相关的问题是,为什么这些不被定义为常量?
NilClass
, TrueClass
and FalseClass
having one instance each, namely nil
, true
and false
, which are constants, what is the purpose of having these classes? Why cannot they be instances of the Object
class, and all the relevant methods be simply defined as singleton methods on nil
, true
and false
? A related question is, why are these not defined as constants?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它遵循“一切都是对象”和“对象由它们所属的类来专门化”的思想。
nil
、true
和false
都是对象(因此是带有方法的类的实例化)。它们是 1) 相应类型的唯一居民,并且是 2) 不可变对象允许实现优化 - 事实上,不是一个nil
够了吗?一条有用的错误消息,没有专门针对值:
x.class
“正常工作”。我很高兴它说
NilClass
:-)这种类实例方法还使得重新打开
NilClass
——无论好坏 ——都变得简单并且与它可能的方式一致对其他类型进行。至少从 Ruby 1.9.2 开始,不可能重新分配
true
、false
或nil
(Python 2.x 允许重新分配) True/False 赋值,但 Python 3.x 中没有)。请注意,由于true/false/nil
不是常量,因此它们可以优化为 AST(或实现使用的任何内容)作为“文字值”,而无需常量外观-向上。快乐编码。
It keeps with the idea that "everything is an object" and "objects are specialized by the classes they are instances of".
nil
,true
, andfalse
are all objects (and are thus instantiations of a class with methods). The imposition that they are 1) the sole inhabitants of the respective type and are 2) immutable objects allows for implementation optimizations -- and really, isn't onenil
enough?A helpful error message without specialization for the values:
x.class
"just works".I am glad it said
NilClass
:-)This class-instance approach also makes re-opening
NilClass
-- for better or worse -- as easy and consistent with how it might be done for other types.At least as of Ruby 1.9.2 it is not possible to re-assign
true
,false
ornil
(Python 2.x allowed re-assignment of True/False, but does not in Python 3.x). Note that becausetrue/false/nil
are not constants they can be optimized into the AST -- or whatever the implementation uses -- as "literal values" without a constant look-up.Happy coding.
Ruby 有时采用“只获取一个对象并向其添加一些单例方法”的方法
:
我不知道为什么他们不使用
true
、false
或nil 来执行此方法代码>.也许是因为人们需要理解这些对象(根据 pst 的答案),而人们不需要理解“主要”(?)对象。
Ruby takes the approach of "just take an object and add some singleton methods to it" some of the time:
gives
I don't know why they don't do this approach with
true
,false
ornil
. Maybe because people need to understand these objects (as per pst's answer), whereas people don't need to understand the "main" (?) object.