Ruby Monstas


Scopes

Scopes

After learning how to write methods, we need to have a look at a concept called scopes.

In the following interactive exercise, we'll learn what this means.

Interactive exercise ๐Ÿ‡ฌ๐Ÿ‡ง

What's the output of following script:

greeting = "Hello!"
puts greeting
Output
Hello!
Nothing special so far

Interactive exercise ๐Ÿ‡ซ๐Ÿ‡ท

def greet_in_french
  greeting = "Bonjour!"
  puts greeting
end

greet_in_french
Output
Bonjour!
Still nothing new...

Interactive exercise ๐Ÿ‡จ๐Ÿ‡ฟ

greeting = "Hello!"

def greet_in_czech
  greeting = "Ahoj!"
  puts greeting
end

greet_in_czech
puts greeting
Output
Ahoj!
Hello!
Here we have 2 scopes: The method body (1) and everything except the method body (2).
Each scope contains a local variable named
greeting
.
These variables can hold different values and don't interfere with each other.

Interactive exercise ๐Ÿ‡ฏ๐Ÿ‡ต

greeting = "Hello!"

def greet_in_japanese
  greeting = "ใ“ใ‚“ใซใกใฏ" # Kon'nichiwa
  puts greeting
end

greeting = "Good day!"

greet_in_japanese
puts greeting
Output
ใ“ใ‚“ใซใกใฏ
Good day!
In this example, the local variable on line 1 is re-assigned on line 8.
The local variable on line 4 is not affected, because it "lives" in its own scope.

Interactive exercise ๐Ÿ‡ณ๐Ÿ‡ด

greeting = "Hei der!"

def greet_in_norwegian
  puts greeting
end

greet_in_norwegian
Output
NameError (undefined local variable or method `greeting' for main:Object)
On line 4, we can not access the local variable on line 1, because it lives in a different scope.

Summary

  • A scope is an area where variables "live in".
  • We also call them local variables.
  • Each method has its own scope.
  • A variable name may exist in multiple scopes and can hold different values.

There is a way how we can read variables from a global scope.
This is covered in a different lesson. ๐Ÿ‘ทโ€โ™€๏ธ

Additional Resources

Ruby For Beginners: Scopes

What questions do you have?