SharkLaser
SharkLaser

Reputation: 773

Why do methods from Enumerable return an Enumerator?

Many methods from Ruby's Enumerable will return an Enumerator if you don't pass a block.

Example:

array = [1,2,3]
array.each.class
# => Enumerator
array.each { |n| n+10 }.class
# => Array

What is the reason for this? Why wouldn't they just return nil or something else signaling that no block was given.

Upvotes: 0

Views: 82

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Enumerators Give You Control Over Iteration

Among other things, Enumerators give you control over when you iterate over an object. Sometimes you don't need the iteration to happen now, so you store the Enumerator for later use rather than immediately passing the results to a block. Other times, you may want finer-grained control over the iteration process itself.

One of the most useful (and underused) methods is Enumerable#lazy. Rather than reifying a million integers from a range all at once, you can grab one at a time when you need it. For example:

enum = (1..1_000_000).lazy
enum.next #=> 1
enum.next #=> 2
enum.peek #=> 3
enum.next #=> 3

This has obvious performance implications. Your mileage may vary.

Upvotes: 4

Related Questions