Question

I just encounter this piece of code

Enumerator.new((1..100), :take, 5).to_a
# => []

Does anyone know why it returns an empty array and not an array of 5 integers?

Was it helpful?

Solution

From the docs, Enumerator#new:

new(obj, method = :each, *args)

In the second, deprecated, form, a generated Enumerator iterates over the given object using the given method with the given arguments passed.

Use of this form is discouraged. Use Kernel#enum_for or Kernel#to_enum instead.

This second usage (which you should not use according to the documentation), needs a each-like method (that's it, one that yields values). take returns values, but does not yield them, so you get an empty enumerable.

Note that in Ruby 2 it will be plain simple to perform a lazy take:

2.0.0dev> xs = (1..100).lazy.take(5)
#=> #<Enumerator::Lazy: #<Enumerator::Lazy: 1..100>:take(5)>
2.0.0dev> xs.to_a
#=> [1, 2, 3, 4, 5] 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top