Enumerators

Contents
External iteration
Lazy chains
each_with_object
A Fibonacci enumerator

External iteration

Calling each without a block returns an Enumerator, which is an iterator you drive by hand.

Each next call returns the following element, which helps when input arrives in steps.

enum = [1, 2, 3].each puts enum.next puts enum.next

ruby enum_demo.rb

1
2

Lazy chains

Long or endless sequences need lazy chains, so values are computed only on demand.

The lazy call turns the endless range into a lazy enumerator, and first pulls just five doubled values.

result = (1..).lazy.map { |n| n * 2 }.first(5) p result

ruby lazy_demo.rb

[2, 4, 6, 8, 10]

each_with_object

The each_with_object method folds a collection into a memo object that the block mutates.

A hash with default zero counts letters without any key checks.

counts = ["a", "b", "a"].each_with_object(Hash.new(0)) do |letter, memo| memo[letter] += 1 end p counts

ruby counts_demo.rb

{"a"=>2, "b"=>1}

A Fibonacci enumerator

Custom sequences come from Enumerator.new with a block that yields each value.

An endless loop is safe here because first stops the sequence after six numbers.

fib = Enumerator.new do |y| a = 0 b = 1 loop do y << a a, b = b, a + b end end puts fib.first(6).inspect

ruby fib_demo.rb

[0, 1, 1, 2, 3, 5]

Next: Pattern matching

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: