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.
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
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' # 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
Finally, 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