我最近发现您可以检测一个类/模块是否包含另一个类/模块。例如 Array
是 Enumerable
所以你可以这样做
Array < Enumerable # true
String
但是不可枚举
String < Enumerable #nil
这里究竟发生了什么?这种语法在 ruby 中如何工作?
最佳答案
以下是获取类的祖先链的方法:
>> Array.ancestors
=> [Array, Enumerable, Object, Kernel, BasicObject]
如果一个类是祖先链中另一个类的“左”,则 < 方法返回 true,否则返回 false:
>> Array < Object
=> true
>> Array < Enumerable
=> true
如果一个类不是“左”类或祖先链中的另一个类,则 < 方法返回 false。
>> Enumerable < Array
=> false
>> Array < Array
=> false
Enumerable 是混入 Array 类的模块,但未混入 String 类。
>> Array.ancestors
=> [Array, Enumerable, Object, Kernel, BasicObject]
>> String.ancestors
=> [String, Comparable, Object, Kernel, BasicObject]
如果将 Enumerable 模型包含到 String 类中,它也会返回 true。
class String
include Enumerable
end
# Enumerable is now included in String
String < Enumerable #true
语法之所以有效,是因为语法糖。在 Ruby 中一切皆对象,语法糖甚至用于加法等基本操作:
>> 3 + 4
=> 7
>> 3.+(4)
=> 7
< 方法的显式语法如下:
>> Array.<(Object)
=> true
>> Array.send(:<, Object)
=> true
关于ruby - Foo < Ruby 中的 Bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17730655/