Skip to content

Instantly share code, notes, and snippets.

@theozaurus
Last active June 3, 2016 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theozaurus/354c755470b1ef7e1c34234c90567f9e to your computer and use it in GitHub Desktop.
Save theozaurus/354c755470b1ef7e1c34234c90567f9e to your computer and use it in GitHub Desktop.
Lazy streams
class A
def initialize(*processors)
@processors = processors
end
def call(list)
@processors.inject(0) { |acc, p|
acc + p.call(list)
}
end
end
class B
def initialize(multiplier)
@multiplier = multiplier
end
def call(list)
list.map { |i|
i * @multiplier
}.inject(0) { |acc, i|
puts "B with multipler: #{@multiplier}, adding: #{i}"
acc + i
}
end
end
A.new(B.new(1), B.new(2)).call([1, 2, 3, 4, 5].lazy)
# => 45
# B with multipler: 1, adding: 1
# B with multipler: 1, adding: 2
# B with multipler: 1, adding: 3
# B with multipler: 1, adding: 4
# B with multipler: 1, adding: 5
# B with multipler: 2, adding: 2
# B with multipler: 2, adding: 4
# B with multipler: 2, adding: 6
# B with multipler: 2, adding: 8
# B with multipler: 2, adding: 10
# Desired output
# => 45
# B with multipler: 1, adding: 1
# B with multipler: 2, adding: 2
# B with multipler: 1, adding: 2
# B with multipler: 2, adding: 4
# B with multipler: 1, adding: 3
# B with multipler: 2, adding: 6
# B with multipler: 1, adding: 4
# B with multipler: 2, adding: 8
# B with multipler: 1, adding: 5
# B with multipler: 2, adding: 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment