Instance Variables
Instance variables hold state for each individual object. Prefix them with @ โ that's what makes them belong to the instance rather than the class.
class Player
def initialize(name)
@name = name
@health = 100
end
end
p1 = Player.new("Alice")
p2 = Player.new("Bob")
# Each player has its own @name and @health
Every object gets its own copy. Changing one doesn't affect the other.
p1.instance_variable_get(:@name) # => "Alice"
p2.instance_variable_get(:@name) # => "Bob"
Instance variables are private by default. You can't reach in and grab @name from outside the object โ that would break encapsulation. Instead, you use methods to access them:
class Player
attr_reader :name
attr_accessor :health
def initialize(name)
@name = name
@health = 100
end
end
player = Player.new("Alice")
player.name # => "Alice"
player.health # => 100
attr_reader creates a getter, attr_writer creates a setter, and attr_accessor creates both. These are just shortcuts for writing the methods yourself.
You can list all instance variables on any object with instance_variables:
player.instance_variables
# => [:@name, :@health]
This is Ruby's way of keeping things tidy. Your internal state stays protected, and you control how the outside world interacts with it through your methods.
Try it Yourself ->