Transducers in Ruby explained

Transducers in Ruby explained
Average rating: 0
(0 votes)

Thanks! You’ve rated this material!

When it comes to Ruby we don’t leave anything unclear and unexplained. Especially such complicated notions as transducers. Today we’ll try to fix that. Transducers in Ruby explained. How to reuse the transformation and compose it with others?

Let’s start with the definitions of transducers. There are composable and efficient data transformation functions that don’t create intermediate collections. There are such transformations like mapselect and reduce. We can compose them together. But the problem is that these functions have different signatures. This is why all of them need to be generalized and it can be done in terms of reduce.

map and select can be implemented using reduce. Here’s map implementation:

map_inc_reducer = -> result, input {
  result.push(input + 1)
.reduce([], &map_inc_reducer)
# =>

push and + are both reducing functions, they take initial value and input, and reduce them to a single output value.

Check out this great material where you can find all examples and conversions to Ruby code. FInd more about Transducer protocol which allows different libraries to connect together.

And meet Scientist Ruby library for refactoring critical paths. You will need it!

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

    Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
    Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
    Kharkiv Otakara Yarosha 22, 61000, Kharkiv, Ukraine