Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Functional Patterns in Ruby
What will be the output of the following Ruby code?
class Box
  def initialize(value)
    @value = value
  end

  def add(x)
    @value += x
    self
  end

  def multiply(x)
    @value *= x
    self
  end

  def value
    @value
  end
end

box = Box.new(2)
result = box.add(3).multiply(4).value
puts result
A20
B14
C10
D8
Step-by-Step Solution
Solution:
  1. Step 1: Trace the add method

    Start with @value = 2. add(3) adds 3: 2 + 3 = 5, returns self.
  2. Step 2: Trace the multiply method

    multiply(4) multiplies @value by 4: 5 * 4 = 20, returns self.
  3. Step 3: Call value method

    value returns @value which is 20.
  4. Final Answer:

    20 -> Option A
  5. Quick Check:

    2 + 3 = 5; 5 * 4 = 20 [OK]
Quick Trick: Follow each method step-by-step, remember self returns object [OK]
Common Mistakes:
  • Forgetting that add and multiply return self
  • Calculating operations in wrong order
  • Returning intermediate values instead of final

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes