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 then
s.
"something"
.then {|str| str.chars.map {|x| x.ord + 1 }}
.then {|ords| ords.map {|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!