在 Ruby 中,Enumerable 模块混合到集合类中,并依赖于提供 each
方法的类,该方法产生集合中的每个项目。
好吧,如果我想在我自己的类中使用 Enumerable,我将只实现 each
[1]:
class Colors
include Enumerable
def each
yield "red"
yield "green"
yield "blue"
end
end
> c = Colors.new
> c.map { |i| i.reverse }
#=> ["der", "neerg", "eulb"]
这按预期工作。
但是,如果我用 Enumerable 重写现有类上的 each
方法,它不会破坏 map
等函数。为什么不呢?
class Array
def each
puts "Nothing here"
end
end
> [1,2,3].each {|num| puts num }
#=> "Nothing here"
> [1,2,3].map {|num| num**2 }
#=> [1,4,9]
[1]:来自http://www.sitepoint.com/guide-ruby-collections-iii-enumerable-enumerator/
最佳答案
Enumerable
的 map
实现确实使用了 each
,但是没有什么可以阻止扩展类用它自己的实现覆盖它不要使用each
。
在这种情况下,出于效率原因,Array
确实提供了自己的 map
实现。
关于ruby - `map` 是否使用 `each`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25476542/