Created
March 23, 2012 13:22
-
-
Save betawaffle/2170574 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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