4

Many methods in Ruby array return an enumerator when invoked without parameters or blocks (index, keep_if, each, drop_while and many more).

  • When is it appropriate to use methods in this form, as opposed to calling them with a block?

2 Answers 2

5

From the docs to Enumerator:

Most methods have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator wrapping the iteration.

This allows you to chain Enumerators together. For example, you can map a list’s elements to strings containing the index and the element as a string via:

puts %w[foo bar baz].map.with_index {|w,i| "#{i}:#{w}" }
# => ["0:foo", "1:bar", "2:baz"]

An Enumerator can also be used as an external iterator. For example, Enumerator#next returns the next value of the iterator or raises StopIteration if the Enumerator is at the end.

e = [1,2,3].each   # returns an enumerator object.
puts e.next   # => 1
puts e.next   # => 2
puts e.next   # => 3
puts e.next   # raises StopIteration

I'm sorry for copy-paste, but I couldn't explain better.

Sign up to request clarification or add additional context in comments.

Comments

3

The main original reason for the Enumerator class to exist is method chaining:

array.each.with_object [[], []] { |element, memo| ... }

So basically, you don't need to worry about that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.