Bird
0
0

Find the problem in this Ruby code snippet:

medium📝 Debug Q7 of 15
Ruby - Advanced Metaprogramming
Find the problem in this Ruby code snippet:
class Calculator
  def initialize
    @value = 10
    define_method(:add) { |x| @value + x }
  end
end

calc = Calculator.new
puts calc.add(5)
AMissing parentheses in define_method call
BThe add method does not update @value, only returns sum
CCannot pass parameters to define_method block
DInstance variable @value is not initialized
Step-by-Step Solution
Solution:
  1. Step 1: Analyze add method behavior

    The block returns @value + x but does not assign the result back to @value.
  2. Step 2: Understand expected behavior

    If the goal is to update @value, the method should assign the sum to @value.
  3. Final Answer:

    The add method does not update @value, only returns sum -> Option B
  4. Quick Check:

    Method returns sum but does not change @value [OK]
Quick Trick: define_method block can take parameters like normal methods [OK]
Common Mistakes:
  • Expecting @value to change without assignment
  • Thinking define_method disallows parameters
  • Ignoring instance variable initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes