Skip to content

Instantly share code, notes, and snippets.

@taq
Created November 3, 2012 19:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taq/4008439 to your computer and use it in GitHub Desktop.
Save taq/4008439 to your computer and use it in GitHub Desktop.
Natural numbers enumerator on Ruby 2.0 using lazy evaluation
natural_numbers = Enumerator.new do |yielder|
number = 1
loop do
yielder.yield number
number += 1
end
end
p natural_numbers.lazy.select { |n| n.odd? }.take(5).to_a # => [1, 3, 5, 7, 9]
p natural_numbers.lazy.map { |n| n*2 }.take(5).to_a # => [2, 4, 6, 8, 10]
p natural_numbers.lazy.select { |n| n.odd? }.map { |n| n*2 }.take(5).to_a # => [2, 6, 10, 14, 18]
p natural_numbers.lazy.select { |n| n.odd? }.select { |n| n<10 }.take(5).to_a # => [1, 3, 5, 7, 9]
p natural_numbers.lazy.map { |n| n*3 }.select { |n| n.odd? }.take(5).to_a # => [3, 9, 15, 21, 27]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment