0
0
Rubyprogramming~5 mins

Instance variables (@) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A@
B$
C#
D&
Where are instance variables typically declared in a Ruby class?
AOutside the class
BInside the initialize method
CInside a global method
DIn a local variable
Can you access an instance variable directly from outside the object?
ANo, you need a method to access it
BYes, always
COnly if it starts with $
DOnly inside a module
What does @name represent inside a Ruby class?
AA constant
BA local variable
CA global variable
DAn instance variable
If you create two objects from the same class, do they share the same instance variables?
AOnly if they are global
BYes, instance variables are shared
CNo, each object has its own instance variables
DOnly if declared outside methods
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.