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.
Practice
(1/5)
1. What does the >> operator do when used with two Procs in Ruby?
easy
A. It merges two Procs into one that runs them both in parallel.
B. It creates a new Proc that runs the first Proc, then passes its result to the second Proc.
C. It swaps the order of execution of two Procs.
D. It deletes the second Proc and keeps only the first.
Solution
Step 1: Understand Proc composition operator
The >> operator chains two Procs so the output of the first becomes input of the second.
Step 2: Explain the effect of chaining
Calling the combined Proc runs the first, then passes its result to the second, producing a final result.
Final Answer:
It creates a new Proc that runs the first Proc, then passes its result to the second Proc. -> Option B
Quick Check:
Proc composition = chaining with >> [OK]
Hint: Remember >> chains Procs passing output as input [OK]
Common Mistakes:
Thinking >> runs Procs in parallel
Assuming >> swaps execution order
Believing >> deletes one Proc
2. Which of the following is the correct syntax to compose two Procs p1 and p2 in Ruby?
easy
A. combined = p1 >> p2
B. combined = p1 >>> p2
C. combined = p1 << p2
D. combined = p1 >> p2.call
Solution
Step 1: Recall correct Proc composition operator
The operator to compose Procs is >>, which is written as >> but in Ruby code it is >> (two greater-than signs).
Step 2: Check each option
combined = p1 >> p2 uses >> correctly. combined = p1 >>> p2 uses three > which is invalid. combined = p1 << p2 uses << which is not for composition. combined = p1 >> p2.call calls p2 immediately, which is wrong.
Final Answer:
combined = p1 >> p2 -> Option A
Quick Check:
Proc composition syntax = p1 >> p2 [OK]
Hint: Use exactly two > signs to compose Procs [OK]