Function Composition in Ruby

Sreedev Kodichath
TarkaLabs TIL
Published in
Feb 7, 2022

--

I was going through some functional programming content & I came across a Wikipedia article on Function Composition. I was surprised to learn that Ruby has special operators for function composition. This is the recommended way to compose procs/functions in Ruby 2.6

f = proc{|x| x + 2}
g = proc{|x| x * 3}
(f << g).call(3) # -> 11; identical to f(g(3))
(f >> g).call(3) # -> 15; identical to g(f(3))

I’ve been using Ruby for a long time and to this day, I run into such surprises now & then.

--

--

Sreedev Kodichath
TarkaLabs TIL

Senior Software Engineer @ Tunecore. Ruby, Elixir, Javascript C & Rust. Amateur Radio Operator — KD2ZWB/VU2JWE. www.sree.dev. Brooklyn, NYC.