Bird
0
0

What is the issue with this Ruby class code?

medium📝 Debug Q6 of 15
Ruby - Classes and Objects
What is the issue with this Ruby class code?
class Laptop
def initialize(brand)
@brand = brand
end
def display
puts brand
end
end

laptop = Laptop.new('Dell')
laptop.display
AThe initialize method should not use an instance variable.
BThe instance variable @brand is not accessible in the display method because 'brand' is used without '@'.
CThe display method should return @brand instead of puts.
DThe class should inherit from another class to access instance variables.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the initialize method

    The instance variable @brand is correctly assigned in initialize.
  2. Step 2: Check the display method

    The method tries to puts 'brand' without '@', which refers to a local variable or method, not the instance variable.
  3. Final Answer:

    The display method should use @brand instead of brand -> Option B
  4. Quick Check:

    Instance variables require '@' prefix to be accessed inside methods [OK]
Quick Trick: Always use '@' to access instance variables inside methods [OK]
Common Mistakes:
  • Using variable name without '@' inside instance methods
  • Confusing local variables with instance variables
  • Assuming instance variables are accessible without '@'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes