p.matsinopoulos
p.matsinopoulos

Reputation: 7810

How can I get the next n number of elements using a Ruby enumerator?

I am trying to get the next n number of elements using a Ruby enumerator, with this:

a = [1, 2, 3, 4, 5, 6]
enum = a.each
enum.next(2) # expecting [1, 2]
enum.next(2) # expecting [3, 4]

But #next does not support that.

What is the correct Ruby way to do that?

Upvotes: 1

Views: 138

Answers (3)

ulysses_rex
ulysses_rex

Reputation: 420

If you want the next N number of elements from an enumerator, while also forwarding the enumerator's internal pointer:

Array.new(n) { enum.next }

Note that if you exceed the enumerator's max bound when doing this, a StopIteration exception will be raised.

But it won't raise if you're using a cyclic enumerator. Example:

enum = (1..3).cycle

Array.new(6) { enum.next }
# => [1, 2, 3, 1, 2, 3]

Upvotes: 0

sawa
sawa

Reputation: 168081

a = [1, 2, 3, 4, 5, 6]
enum = a.dup
enum.shift(2) # => [1, 2]
enum.shift(2) # => [3, 4]

Upvotes: 1

Wand Maker
Wand Maker

Reputation: 18762

You can use take method

enum.take(2)

If you need slices of two elements, you could do:

e = enum.each_slice(2)
p e.next
#=> [1, 2]
p e.next
#=> [3, 4]

Upvotes: 5

Related Questions