Skip to content

Instantly share code, notes, and snippets.

@betawaffle
Created March 23, 2012 13:22
Show Gist options
  • Save betawaffle/2170574 to your computer and use it in GitHub Desktop.
Save betawaffle/2170574 to your computer and use it in GitHub Desktop.
module Enumerable
def lazy_map mapper = nil, &block
return to_enum(:lazy_map, block) unless mapper
return to_enum(:lazy_map, mapper) unless block
each do |*args|
yield mapper.call(*args)
end
end
end
# Allows applying multiple transformations in one iteration
# Examples:
[1, 2, 3, 4].lazy_map { |x| x + 1 }
# => #<Enumerator: ...>
[1, 2, 3, 4].lazy_map { |x| x + 1 }.to_a
# => [2, 3, 4, 5]
[1, 2, 3, 4].lazy_map { |x| x + 1 }.lazy_map { |y| y + 1 }.to_a
# => [3, 4, 5, 6]
# Equivalent to:
[1, 2, 3, 4].map { |x| x + 1 + 1 }
# But it gets better!
# More to come...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment