Bird
0
0

What is the output of this Ruby code combining OOP and functional style?

medium📝 Predict Output Q13 of 15
Ruby - Functional Patterns in Ruby
What is the output of this Ruby code combining OOP and functional style?
class Calculator
  def initialize(value)
    @value = value
  end

  def double
    @value * 2
  end

  def apply(func)
    func.call(@value)
  end
end

calc = Calculator.new(5)
puts calc.double
puts calc.apply(->(x) { x + 3 })
A10 8
B10 15
C5 8
DError: undefined method
Step-by-Step Solution
Solution:
  1. Step 1: Understand the Calculator class methods

    The double method returns @value * 2, so for 5 it returns 10. The apply method calls the passed function with @value.
  2. Step 2: Evaluate the output of puts statements

    calc.double prints 10. calc.apply calls the lambda adding 3 to 5, so prints 8.
  3. Final Answer:

    10 8 -> Option A
  4. Quick Check:

    double = 10, apply adds 3 = 8 [OK]
Quick Trick: Remember lambdas called with .call and return values [OK]
Common Mistakes:
  • Confusing lambda call syntax
  • Expecting apply to modify @value
  • Mixing up output values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes