Zoonk icon

What's the scope of a local variable in Ruby?

Created by Will Ceolin
Created on Feb 17, 20 - Updated on Feb 17, 20

Understanding a variable's scope is important to know when it's going to be called and what values can be changed.

You can have a variable with the same in different places of your code but its value might be different depending on where you call it:

name = "Leonardo"

class ScopeLesson
  name = "Nikola"
  puts "class scope: #{name}"
end

Now run the following and think about what should be displayed on the screen:

puts "top-level: #{name}"
ScopeLesson.new

This will print out two different values for the variable because we're calling it both inside and outside the class scope:

=> class scope: "Nikola"
=> top-level: "Leonardo"

The same happens if we redeclare our variable inside a method's scope:

name = "Leonardo"

class ScopeLesson
  name = "Nikola"

  def my_method
    name = "Albert"
    puts "method scope: #{name}"
  end

  puts "class scope: #{name}"
end

Let's call to see what happens:

puts "top-level: #{name}"
ScopeLesson.new.my_method

=> class scope: "Nikola"
=> top-level: "Leonardo"
=> method scope: "Albert"

We now have three different values for the variables because they use different scopes. When it's called outside the class, it gets its original value (Leonardo); when it's called inside the class but outside our method, it gets its class value (Nikola); but when we call it inside our method, then we get the value we assigned to it there (Albert).