Created
May 18, 2017 17:42
-
-
Save f-mer/5c084862a46faed7f2822c4f1c5ec941 to your computer and use it in GitHub Desktop.
Transforming data with streams in Ruby
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
| 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