[英]Ruby Module has access to class methods it was required in?
I don't quite understand how this works: 我不太明白这是如何工作的:
module Perimeter
def perimeter
sides.inject(0) { |sum, side| sum + side }
end
end
class Rectangle
include Perimeter
def initialize(length, breadth)
@length = length
@breadth = breadth
end
def sides
[@length, @breadth, @length, @breadth]
end
end
class Square
include Perimeter
def initialize(side)
@side = side
end
def sides
[@side, @side, @side, @side]
end
end
When you call Rectangle.new(2, 3).perimeter
it returns 10 as expected. 当您调用
Rectangle.new(2, 3).perimeter
它会按预期返回10。
In this case, the module gets the arguments by calling the sides
method from the class. 在这种情况下,模块通过从类中调用
sides
方法来获取参数。 How can a module have access to that method? 模块如何访问该方法? Is it because of
include
keyword? 是因为
include
关键字?
How can a module have access to that method?
模块如何访问该方法?
That's exactly what modules do. 这正是模块所做的。 Basically, you can define a bunch of methods in a module, then include it, and the end result is as if those methods were in your class directly.
基本上,您可以在模块中定义一组方法,然后包含它,最终结果就好像这些方法直接在您的类中一样。
If you want more technical, including a module injects it into your class' ancestors chain. 如果你想要更多技术,包括一个模块将它注入你的班级祖先链。
Rectangle.ancestors # => [Rectangle, Perimeter, Object, Kernel, BasicObject]
You might be familiar with Enumerable
module. 您可能熟悉
Enumerable
模块。 It contains many useful methods, like reduce
, map
, count
and others. 它包含许多有用的方法,如
reduce
, map
, count
等。 They're all implemented with method each
and that's the one method that Enumerable module does not implement. 他们都用方法来实现
each
就是这样可枚举模块没有实现的一种方法。 It's the missing piece. 这是缺失的一块。 Now, if you have a class (some kind of collection, perhaps. Genealogy tree or something) and it implements
each
, you can include Enumerable
in that class and voilà, now you can map
your collection. 现在,如果你有一个类(某种类型的集合,也许是。家谱树或其他东西)并且它实现了
each
,你可以在该类中包含Enumerable
,现在你可以map
你的集合。 Same thing in your case with perimeter
and sides
. 在您的情况下,
perimeter
和sides
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.