3 ms·
A Guide to Function Composition in Ruby
- pmontra 8y agoTL;DR 2.6.0 :001 > double = ->(number) { number * 2 } => #<Proc:0x000000000135b488@(irb):1 (lambda)> 2.6.0 :002 > square = ->(number) { number * number } => #<Proc:0x000000000135deb8@(irb):2 (lambda)> 2.6.0 :003 > (double >> square).call(3) => 36 2.6.0 :004 > (double << square).call(4) => 18 However that ().call() syntax is quite ugly. IMHO something like this is much better 2.6.0 :005 > class Object 2.6.0 :006?> def pipe(f) 2.6.0 :007?> f.call(self) 2.6.0 :008?> end 2.6.0 :009?> end => :pipe 2.6.0 :010 > 3.pipe double >> square => 36 2.6.0 :011 > 3.pipe double << square => 18 But I don't like to monkey patch Object, especially with a method name that's going to break many libraries and gems. I'd rather have Ruby allowing us to write 3 >> double >> square like Elixir's iex(1)> defmodule Demo do ...(1)> def double(x), do: x*2 ...(1)> def square(x), do: x*x ...(1)> end iex(2)> 3 |> Demo.double |> Demo.square 36