Welcome back! In the last lesson, we talked about how to return values from functions. Now, let’s dive into another critical concept in Ruby programming: variable scope. This lesson will help you understand the difference between local and global variables and how to use them effectively. Understanding variable scope is crucial for writing readable and bug-free code.
In this lesson, you'll learn:
Here's a glimpse of an example to get you started:
Ruby1$global_destination = "Mount Fuji" # Global variable 2 3def report_destination 4 local_destination = "Sahara Desert" # Local variable 5 puts "Local destination is #{local_destination}." 6 puts "Global destination is #{$global_destination}." 7end 8 9report_destination
In the above example, you’ll see how both local and global variables are declared and used within a function. Notice that we use the $
symbol to declare a global variable.
Notice, that if we try to do the same thing with a regular variable, we will get an error:
Ruby1another_destination = "Mount Kilimanjaro" # Local variable 2 3def report_destination 4 puts "New destination is #{another_destination}." # Error: undefined local variable or method `another_destination' 5end 6 7report_destination
In this case, the another_destination
variable is not accessible within the function because it is a local variable.
Similarly, a variable declared inside a function is not accessible outside the function:
Ruby1def report_destination 2 local_destination = "Sahara Desert" # Local variable 3end 4 5puts local_destination # Error: undefined local variable or method `local_destination'
In this case, the local_destination
variable is not accessible outside the function because it is a local variable.
Grasping the concept of variable scope is essential for several reasons:
For instance, using global variables for data that need to be accessed across various functions helps maintain state. However, overusing global variables can make your code hard to debug. Local variables, on the other hand, are restricted to the scope of the function, enhancing modularity and reducing the chances of unwanted side effects.
Excited to learn more? Let's proceed to the practice section to solidify these concepts and become adept at managing variable scope in Ruby programs.