The pipeline operator helps you write code that flows step-by-step, making it easier to read and understand.
Pipeline operator concept in Ruby
value |> method1 |> method2 |> method3
The |> operator passes the result of the left side as the first argument to the method on the right.
This operator is available in Ruby 2.6 and later as an experimental feature, and officially introduced in Ruby 3.1.
5 |> ->(x) { x + 1 } |> ->(x) { x * 2 }
"hello" |> :upcase.to_proc |> :reverse.to_proc[1, 2, 3] |> ->(arr) { arr.map { |x| x * 3 } } |> ->(arr) { arr.sum }
This program subtracts 2 from 10, multiplies the result by 5, then converts it to a string with " units" added.
result = 10 |> ->(x) { x - 2 } |> ->(x) { x * 5 } |> ->(x) { x.to_s + " units" } puts result
The pipeline operator makes code easier to read by avoiding nested calls.
You can use lambdas or method references on the right side of |>.
Remember this operator is new in Ruby 3.1, so older Ruby versions won't support it without enabling experimental features.
The pipeline operator |> passes the left value as the first argument to the right method.
It helps write clear, step-by-step code without nested calls.
Use it to improve readability and flow in your Ruby programs.