Bird
0
0

Identify the issue in this Ruby code snippet:

medium📝 Debug Q14 of 15
Ruby - Metaprogramming Fundamentals
Identify the issue in this Ruby code snippet:
class Car
  def initialize
    @speed = 0
  end

  def set_speed(value)
    instance_variable_set(:speed, value)
  end
end

car = Car.new
car.set_speed(50)
puts car.instance_variable_get(:@speed)
AThe variable @speed is not initialized.
BCannot call instance_variable_set inside a method.
CMissing '@' in instance_variable_set argument name.
Dinstance_variable_get should use string, not symbol.
Step-by-Step Solution
Solution:
  1. Step 1: Check instance_variable_set argument

    The argument to instance_variable_set must include '@' prefix to identify the instance variable.
  2. Step 2: Identify the error

    Here, :speed is missing '@', so Ruby will not find the variable and will create a new one without '@', causing unexpected behavior.
  3. Final Answer:

    Missing '@' in instance_variable_set argument name. -> Option C
  4. Quick Check:

    Always include '@' in variable name for instance_variable_set [OK]
Quick Trick: Always prefix variable name with '@' in set/get methods [OK]
Common Mistakes:
  • Omitting '@' in variable name
  • Thinking instance_variable_set can't be used in methods
  • Confusing symbol and string usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes