Ruby and yield_self (next)
Welcome to Cultivate’s Bytesize Blog. Here you will find tasty morsels of useful and cool stuff from our Cultivars.
One of the things that can make a series of operations on data more readable in code is using pipelines. In Elixir we will often use the pipe operator. In Ruby we will chain operations on collections together. For example:
(1..100_000)
.map {|i| i * 3}
.select {|i| i.odd?}
.sum()
Such pipelines could only be consructed using methods existing on the input of each stage. Ruby 2.5 introduced Object#yield_self
, which makes the following possible.
"\ntmp/test.txt\n"
.strip()
.yield_self {|f| File.read(f)}
As yield_self
is not the most intuitive of names, Ruby 2.6 will alias it to Object#then
.
Acknowledgements
James Bell mentioned Object#yield_self
and Object#then
during the December 2018 ScotRUG meetup.