Ruby - Class Object Variables

Introduction

Local variables are specific to the local scope.

Global variables have global scope.

Object instance variables have scope within the current object.

Demo

class Square 
  def initialize(side_length) 
    @side_length = side_length #  w w w . j  a va  2s.  c  om
  end 

  def area 
    @side_length * @side_length 
  end 
end 
a = Square.new(10) 
b = Square.new(5) 
puts a.area 
puts b.area

Result

Object variables are prefixed with an @ symbol.

In the Square class, you assign the side_length provided to the class to @side_length.

@side_length, as an object variable, is then accessible from any other method inside that object.

That's how the area method can then use @side_length to calculate the area of the square represented by the object: