Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Functional Patterns in Ruby
What will this Ruby code print?
p1 = Proc.new { |x| x * 3 }
p2 = Proc.new { |y| y - 4 }
p3 = p2 >> p1
puts p3.call(5)
A3
B33
C15
D11
Step-by-Step Solution
Solution:
  1. Step 1: Understand composition order

    p3 = p2 >> p1 means p3.call(x) = p1.call(p2.call(x)).
  2. Step 2: Calculate output for input 5

    p2.call(5) = 5 - 4 = 1, then p1.call(1) = 1 * 3 = 3.
  3. Step 3: Re-check order

    Wait, the code says p3 = p2 >> p1, so first p2, then p1. So output is 3.
  4. Final Answer:

    3 -> Option A
  5. Quick Check:

    p3.call(5) = 3 [OK]
Quick Trick: Composition applies left Proc first, then right [OK]
Common Mistakes:
  • Applying p1 before p2
  • Mixing up subtraction and multiplication
  • Ignoring composition order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes