What Does @variable Mean in Ruby?

In Ruby, the at-sign (@) before a variable name (e.g. @variable_name) is used to create a class instance variable. These variables are:

  • Only directly accessible within the class instance methods of the class they're defined in;
  • Specific to each instantiated object of the class they're defined in (i.e. each class object instance has a separate copy of these variables).

For example:

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def name
    @name
  end

  def age
    @age
  end
end

person1 = Person.new("bob", 34)
puts "#{person1.name} is #{person1.age} years old"

person2 = Person.new("john", 22)
puts "#{person2.name} is #{person2.age} years old"

From the code above you can see that each instantiated object instance of the Person class has its own copy of the name and age variables (as they're defined as instance variables in the Person class).

Please note that when using Rails, the class instance variables are also available in your views when they're defined in controller classes. This is because the template files are executed within the scope of the related controller instance.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.