Recall & Review
beginner
What is an instance variable in Ruby?
An instance variable in Ruby is a variable that belongs to a specific object (instance) of a class. It starts with the @ symbol and stores data unique to that object.
Click to reveal answer
beginner
How do you declare an instance variable inside a Ruby class?
You declare an instance variable by prefixing the variable name with @ inside any method of the class, usually inside the initialize method.
Click to reveal answer
beginner
Why do instance variables start with @ in Ruby?
The @ symbol tells Ruby that the variable is tied to a specific object instance, not a local or global variable. It helps Ruby keep track of data for each object separately.
Click to reveal answer
intermediate
Can instance variables be accessed directly outside the class?
No, instance variables are private to the object. To access them outside the class, you need to use methods like getters or attr_reader.
Click to reveal answer
beginner
Example: What does this code print?
<pre>class Dog
def initialize(name)
@name = name
end
def speak
"Woof! My name is #{@name}"
end
end
dog = Dog.new("Buddy")
puts dog.speak</pre>It prints: Woof! My name is Buddy
The @name instance variable stores the dog's name and is used inside the speak method.
Click to reveal answer
What symbol is used to start an instance variable in Ruby?
✗ Incorrect
Instance variables in Ruby always start with the @ symbol.
Where are instance variables typically declared in a Ruby class?
✗ Incorrect
Instance variables are usually set inside the initialize method to store object-specific data.
Can you access an instance variable directly from outside the object?
✗ Incorrect
Instance variables are private to the object; you must use methods like getters to access them.
What does @name represent inside a Ruby class?
✗ Incorrect
The @ symbol means the variable is an instance variable tied to the object.
If you create two objects from the same class, do they share the same instance variables?
✗ Incorrect
Each object has its own copy of instance variables, so data is unique per object.
Explain what an instance variable is in Ruby and why it starts with @.
Think about how Ruby keeps data unique for each object.
You got /4 concepts.
Describe how you would use instance variables to store and access a person's name in a Ruby class.
Consider how to keep the name inside the object and show it outside.
You got /4 concepts.