理解 ruby​​ .class 和 .ancestors 方法 [英] Understanding ruby .class and .ancestors methods

查看:30
本文介绍了理解 ruby​​ .class 和 .ancestors 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下定义的类

class Order
end

puts Order.class #-> Class
puts Order.ancestors #-> [Order, Object, Kernel, BasicObject]

puts Order.class.ancestors #->[Class, Module, Object, Kernel, BasicObject]

我的问题是为什么 Order.ancestors 没有在祖先链中显示Class"或Module"?既然Order是Class类的对象,那么Order不应该显示Class的所有祖先吗?

My question is why is it that Order.ancestors doesn't show 'Class' or 'Module' in ancestors chain? Since Order is an object of the class Class, shouldn't Order show all the ancestors of Class?

推荐答案

为此,您需要了解 Ruby 对象模型的外观.

For that you need to see how the Ruby object model looks.

这意味着默认情况下,使用关键字class 创建的类将始终是Object 的子类.Class 不是您的类 Order 的超类,而是类 Class 的一个实例.Module#ancestors 将包括包含在 mod 中的模块列表(包括 mod 本身)和您的类 Order 的超类.

That means the classes created using keyword class will always be the subclass of Object by default. Class is not the superclass of your class Order, rather it is an instance of class Class.Module#ancestors will include list of modules included in mod (including mod itself) and the superclass of your class Order.

class Order;end
Order.superclass # => Object
Order.superclass.superclass # => BasicObject
Order.superclass.included_modules # => [Kernel]

因此,如果您查看输出并理解上述代码,那么您现在应该清楚以下内容:

So if you look at the output and understand the above code,then the below should now be clear to you:

Order.ancestors #-> [Order, Object, Kernel, BasicObject]

现在看,

class Order;end
Order.class # => Class
Order.instance_of? Class # => true
Order.class.superclass # => Module
Order.class.superclass.superclass # => Object
Order.class.superclass.superclass.included_modules # => [Kernel]

因此,如果您查看输出并理解上述代码,那么您现在应该清楚以下内容:

So if you look at the output and understand the above code, then the below should now be clear to you:

Order.class.ancestors #->[Class, Module, Object, Kernel, BasicObject]

也就是说 Order.ancestors 是给你 Order 类的祖先,而 Order.class.ancestors 为您提供 Class 的祖先.

That said Order.ancestors is giving you the ancestors of the class Order,whereas Order.class.ancestors is giving you the ancestors of the Class.

这篇关于理解 ruby​​ .class 和 .ancestors 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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