Skip to content

Instantly share code, notes, and snippets.

@porras
Last active August 29, 2015 14:19
Show Gist options
  • Save porras/e8604cb46c710244a948 to your computer and use it in GitHub Desktop.
Save porras/e8604cb46c710244a948 to your computer and use it in GitHub Desktop.
Lazy comprehension
def comprehend(*enums)
cycles = enums.map(&:cycle)
Enumerator.new do |comprehended|
loop do
value = cycles.map(&:peek)
value = yield value if block_given?
comprehended << value
(cycles.length - 1).downto(0) do |index|
cycles[index].next
break unless cycles[index].peek == enums[index].first
raise StopIteration if index == 0
end
end
end.lazy # requires Ruby > 2.0
end
comprehend(1..2, 4..6) { |a, b| puts "Generating #{a},#{b}"; [a, b] }.select { |a, b| (a + b).odd? }.take(2).each {|i| p i}
# Generating 1,4
# [1, 4]
# Generating 1,5
# Generating 1,6
# [1, 6]
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment