Bird
0
0

Identify the error in this Ruby class that tries to override the * operator:

medium📝 Debug Q14 of 15
Ruby - Operators and Expressions
Identify the error in this Ruby class that tries to override the * operator:
class Multiplier
  def *(other)
    @value * other
  end
end

m = Multiplier.new
puts m * 3
AWrong method name for operator *
BOperator * cannot be overridden
CMissing initialize method to set @value
DCannot multiply by a number
Step-by-Step Solution
Solution:
  1. Step 1: Check class initialization

    The class does not define an initialize method, so @value is never set.
  2. Step 2: Understand the error cause

    When m * 3 runs, @value is nil, causing a NoMethodError for * on nil.
  3. Final Answer:

    Missing initialize method to set @value -> Option C
  4. Quick Check:

    Uninitialized @value causes error [OK]
Quick Trick: Always initialize instance variables before using them [OK]
Common Mistakes:
MISTAKES
  • Assuming operator * cannot be overridden
  • Using wrong method name for operator
  • Not initializing instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes