0
0
Rubyprogramming~5 mins

Pipeline operator concept in Ruby

Choose your learning style9 modes available
Introduction

The pipeline operator helps you write code that flows step-by-step, making it easier to read and understand.

When you want to apply several operations one after another on a value.
When you want to avoid nested function calls that are hard to read.
When you want your code to look like a clear sequence of actions.
When you want to improve code readability for yourself or others.
Syntax
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.

Examples
Add 1 to 5, then multiply the result by 2.
Ruby
5 |> ->(x) { x + 1 } |> ->(x) { x * 2 }
Convert "hello" to uppercase, then reverse the string.
Ruby
"hello" |> :upcase.to_proc |> :reverse.to_proc
Multiply each number by 3, then sum all numbers.
Ruby
[1, 2, 3] |> ->(arr) { arr.map { |x| x * 3 } } |> ->(arr) { arr.sum }
Sample Program

This program subtracts 2 from 10, multiplies the result by 5, then converts it to a string with " units" added.

Ruby
result = 10 |> ->(x) { x - 2 } |> ->(x) { x * 5 } |> ->(x) { x.to_s + " units" }
puts result
OutputSuccess
Important Notes

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.

Summary

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.