在Ruby中使用to_enum创建可枚举对象的好处是什么? [英] What is the advantage of creating an enumerable object using to_enum in Ruby?
问题描述
为什么要通过使用to_enum方法而不是直接使用对象来在Ruby中创建对对象的代理引用?我想不出任何实际用途,试图理解这个概念。有人可以使用它,但是我看到的所有示例似乎都很琐碎。
Why would you create a proxy reference to an object in Ruby, by using the to_enum method rather than just using the object directly? I cannot think of any practical use for this, trying to understand this concept & where someone might use it, but all the examples I have seen seem very trivial.
例如,为什么使用:
"hello".enum_for(:each_char).map {|c| c.succ }
而不是
"hello".each_char.map {|c| c.succ }
我知道这是一个非常简单的示例,没有人有任何真实示例?
I know this is a very simple example, does anyone have any real-world examples?
推荐答案
在没有提供块的情况下,大多数接受块的内置方法将返回枚举数(例如 String#each_char
)。对于这些,没有理由使用 to_enum
;
Most built-in methods that accept a block will return an enumerator in case no block is provided (like String#each_char
in your example). For these, there is no reason to use to_enum
; both will have the same effect.
不过,有些方法不会返回Enumerator。在这种情况下,您可能需要使用 to_enum
。
A few methods do not return an Enumerator, though. In those case you might need to use to_enum
.
# How many elements are equal to their position in the array?
[4, 1, 2, 0].to_enum(:count).each_with_index{|elem, index| elem == index} #=> 2
另一个例子是 Array#product
, #uniq
和 #uniq!
并没有接受块。在1.9.2版中,已对此进行了更改,但是为了保持兼容性,没有块的表单不能返回 Enumerator
。仍然可以手动使用 to_enum
来获取枚举数:
As another example, Array#product
, #uniq
and #uniq!
didn't use to accept a block. In 1.9.2, this was changed, but to maintain compatibility, the forms without a block can't return an Enumerator
. One can still "manually" use to_enum
to get an enumerator:
require 'backports/1.9.2/array/product' # or use Ruby 1.9.2+
# to avoid generating a huge intermediary array:
e = many_moves.to_enum(:product, many_responses)
e.any? do |move, response|
# some criteria
end
to_enum
是在实现自己的迭代方法时。通常,您通常将其作为第一行:
The main use of to_enum
is when you are implementing your own iterative method. You typically will have as a first line:
def my_each
return to_enum :my_each unless block_given?
# ...
end
这篇关于在Ruby中使用to_enum创建可枚举对象的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!