0
0
Rubyprogramming~5 mins

Proc composition in Ruby

Choose your learning style9 modes available
Introduction

Proc composition helps you combine small pieces of code into bigger ones easily.

When you want to run one small task after another in order.
When you want to reuse simple code blocks by joining them.
When you want to make your code cleaner by breaking it into steps.
When you want to pass combined behavior as one unit to methods.
When you want to chain transformations on data step-by-step.
Syntax
Ruby
proc1 = Proc.new { |x| x + 2 }
proc2 = Proc.new { |x| x * 3 }

composed = proc1 >> proc2
result = composed.call(4)

The >> operator chains two Procs so the output of the first is input to the second.

You call the composed Proc with .call and it runs both steps in order.

Examples
This adds 2 to 5 (7), then multiplies by 3 (21), printing 21.
Ruby
add_two = Proc.new { |x| x + 2 }
multiply_three = Proc.new { |x| x * 3 }

combined = add_two >> multiply_three
puts combined.call(5)
This removes spaces then makes text uppercase, printing HELLO.
Ruby
strip = Proc.new { |s| s.strip }
upcase = Proc.new { |s| s.upcase }

format_text = strip >> upcase
puts format_text.call("  hello ")
This squares 3 (9) then doubles it (18), printing 18.
Ruby
square = Proc.new { |x| x * x }
double = Proc.new { |x| x * 2 }

process = square >> double
puts process.call(3)
Sample Program

This program adds 5 to 4 (getting 9), then squares 9 (getting 81), and prints 81.

Ruby
add_five = Proc.new { |n| n + 5 }
square = Proc.new { |n| n * n }

combined_proc = add_five >> square

puts combined_proc.call(4)
OutputSuccess
Important Notes

You can chain many Procs together using >> repeatedly.

Proc composition runs left to right: first Proc, then second, and so on.

Make sure the output type of one Proc matches the input type of the next.

Summary

Proc composition lets you join small code blocks to run in sequence.

Use the >> operator to combine Procs.

Call the combined Proc with .call to run all steps.