Bird
0
0

Given these Procs:

hard📝 Application Q15 of 15
Ruby - Functional Patterns in Ruby
Given these Procs:
p1 = Proc.new { |x| x.to_s }
p2 = Proc.new { |s| s + "!" }
p3 = Proc.new { |str| str.reverse }

How do you compose them so that calling the combined Proc with 5 returns "5!"?
Acombined = p3 >> p2 >> p1
Bcombined = p1 >> p2 >> p3
Ccombined = p1 >> p3 >> p2
Dcombined = p2 >> p1 >> p3
Step-by-Step Solution
Solution:
  1. Step 1: Understand each Proc's effect

    p1 converts number to string, p2 adds "!", p3 reverses string.
  2. Step 2: Find composition order to get "5!"

    "5".reverse = "5", so p1 >> p3 >> p2 gives: "5" -> "5" -> "5!". But p1 >> p2 >> p3: "5" -> "5!" -> "!5". Only A produces "5!".
  3. Final Answer:

    combined = p1 >> p3 >> p2 -> Option C
  4. Quick Check:

    to_s, reverse, then add ! = "5!" [OK]
Quick Trick: Order Procs by desired transformations stepwise [OK]
Common Mistakes:
  • Putting p2 before p3 changes output to "!5"
  • Reversing order causes errors on non-string
  • Ignoring effect of reverse on "5!"

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes