Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active August 29, 2015 14:07
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 havenwood/c5c5b48bd96b77bea53d to your computer and use it in GitHub Desktop.
Save havenwood/c5c5b48bd96b77bea53d to your computer and use it in GitHub Desktop.
Transducer FizzBuzz
require 'transducers'
T = Transducers
fizzducer = T.compose T.map { |n| n % 3 == 0 && n % 5 == 0 && 'FizzBuzz' || n },
T.map { |n| n % 3 == 0 && 'Fizz' || n },
T.map { |n| n % 5 == 0 && 'Buzz' || n },
T.map(:to_s)
T.transduce fizzducer, :puts, STDOUT, 1.upto(5)
#>> 1
#>> 2
#>> Fizz
#>> 4
#>> Buzz
T.transduce fizzducer, :<<, '', [1, 2, 3, 4, 5]
#=> "12Fizz4Buzz"
T.transduce T.compose(fizzducer, T.map { |n| n << "\n" }), :<<, '', 1..5
#=> "1\n2\nFizz\n4\nBuzz\n"
T.transduce T.compose(fizzducer, T.map(:to_i)), :+, 0, 1..5
#=> 7
T.transduce fizzducer, :<<, [], 1.upto(5)
#=> ["1", "2", "Fizz", "4", "Buzz"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment