Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to use methods that return an enumerator in Ruby array?

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?
like image 585
davidrac Avatar asked Feb 19 '23 13:02

davidrac


1 Answers

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.

like image 146
Flexoid Avatar answered Feb 22 '23 03:02

Flexoid