0
0
Rubyprogramming~5 mins

Instance_variable_get and set in Ruby

Choose your learning style9 modes available
Introduction

These methods let you read or change an object's variable from outside the object, even if it's private.

When you want to check or change a variable inside an object without using its normal methods.
When debugging and you need to see what values an object holds inside.
When writing flexible code that works with objects without knowing their exact variables.
When you want to change a variable quickly without adding new methods to the class.
Syntax
Ruby
object.instance_variable_get(:@variable_name)
object.instance_variable_set(:@variable_name, value)

Use a symbol with @ before the variable name, like :@name.

These methods bypass normal access rules, so use carefully.

Examples
Gets the value of the @age variable from the person object.
Ruby
person.instance_variable_get(:@age)
Sets the @name variable inside person to "Alice".
Ruby
person.instance_variable_set(:@name, "Alice")
If the variable does not exist, it returns nil instead of error.
Ruby
obj.instance_variable_get(:@score) # returns nil if @score not set
Sample Program

This program creates a Dog object with name and age. It then reads the name and age using instance_variable_get. Next, it changes the age to 6 using instance_variable_set and prints the new age.

Ruby
class Dog
  def initialize(name, age)
    @name = name
    @age = age
  end
end

dog = Dog.new("Buddy", 5)

# Get instance variables
puts dog.instance_variable_get(:@name)
puts dog.instance_variable_get(:@age)

# Set instance variable
dog.instance_variable_set(:@age, 6)
puts dog.instance_variable_get(:@age)
OutputSuccess
Important Notes

These methods can access variables even if there are no getter or setter methods.

Use symbols with the @ sign to name the variable.

Be careful: changing variables this way can break object rules or cause bugs.

Summary

instance_variable_get reads an object's variable by name.

instance_variable_set changes an object's variable by name.

They let you work with variables directly, even if they are private.