Search⌘ K

Scope of Variables

Explore the different scopes of variables in Ruby, including local, instance, class, and global variables. Understand how each type affects the state and behavior of objects in object-oriented programming, and learn best practices for defining and using them in your Ruby code.

We'll cover the following...

You might have noticed that we used @, also known as the “at” sign, before the state variable. This syntax is used to define instance variables. We already covered this a little bit in previous chapters. But in general, we have three types of variables:

Local variables

Local variables are normally defined inside of a method and not accessible from other methods. For example, the following code will produce the error because the aaa variable isn’t defined in method m2:

Ruby
# Error due to 'aaa' variable
class Foo
def m1
aaa = 123
puts aaa
end
def m2
puts aaa
end
end
foo = Foo.new
foo.m1 # works fine, prints 123
foo.m2 # won't work, variable not defined

Instance variables

Instance variables are of the particular class instance, or variables of a particular object. We can access these variables with at sign @:

Ruby
# No error due to '@'
class Foo
def initialize
@aaa = 123
end
def m1
puts @aaa
end
def m2
puts @aaa
end
end
foo = Foo.new
foo.m1
foo.m2

Instance variables define the state of an object. Nothing prevents us from ...