Today I Learned

A Hashrocket project

Chaining `then` in Ruby 2.6

Ruby 2.5 introduced a method yield_self on an object. The idea is simple, just pass self as the argument to a block.

"something".yield_self {|str| str + "!"}
          .yield_self {|str| str + "!"}
# "something!!"

It yields self and returns the result of the block, unlike tap which yields self and returns self.

yield_self feels technical and wordy. Ruby 2.6 introduces an alias for yield_self, then. then feels like something that could mimic the pipe operator (|>) in Elixir. Data transformations can be just a series of thens.

.then {|str| {|x| x.ord + 1 }}
.then {|ords| {|x| x.chr }}
.then {|chars| chars.join } 
.then {|str| str + "!" }
.then {|str| str + "!" }
# tpnfuijoh!!

In some cases where a data transformation takes multiple steps, this coding style might make your could cleaner and more intentional.

I look forward to seeing then in your code!

Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. Contact us and find out how we can help you.