Skip to content

Instantly share code, notes, and snippets.

@f-mer
Created May 18, 2017 17:42
Show Gist options
  • Select an option

  • Save f-mer/5c084862a46faed7f2822c4f1c5ec941 to your computer and use it in GitHub Desktop.

Select an option

Save f-mer/5c084862a46faed7f2822c4f1c5ec941 to your computer and use it in GitHub Desktop.
Transforming data with streams in Ruby
class Stream
def initialize(*segments, &blk)
@source = segments.shift
@sink = segments.pop
@transforms = segments
run(&blk) if block_given?
end
def run(&blk)
@source.each do |input|
output = @transforms.reduce(input) { |n, transform| transform.(n) }
result = @sink.(output)
blk.(input, output, result)
end
end
end
class Mult
def initialize(opts)
@with = opts[:with]
end
def call(input)
input * @with
end
end
class Pow
def call(input)
input * input
end
end
Stream.new((1..10).each, Pow.new, Mult.new(with: 2)) do |input, output, result|
puts [input, output, result].inspect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment