What Does @variable Mean in Ruby?

Learn what the at-sign (@) before a variable name means 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 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 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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.