Ruby provides a mechanism for tapping into the program at runtime to determine the list of defined local and global variables. Ruby provides two methods to get all declared variables in a local or global scope.
Kernel#local_variables
The local_variables
is available globally in your ruby programmes.
x = 5
puts local_variables
# => [:x]
the local_variables
method will get the variables in the current local scope. So, for something like
y = 6
def do_something
x = 5
puts local_variables
end
do_something
local_variables
The first line printed to the console will be the local variables inside do_something
. The second print will be the local variables in the current scope, namely y
.
Kernel#global_variables
In Ruby, a global variables is a variable that starts with a dollar sign $
. Ruby has a set of built-in globals available for us already.
puts global_variables
You can add to the list of global variables by creating your own global variables, tho you might not want to do that.
$my_global_variable = "Custom global"
global_variables.find { |glob| glob == :$my_global_variable }
# => :$my_global_variable
Notice: All variables are stored as a Symbol.
Bonus content, the _
local variable in irb sessions.
When you launch an irb session and log the local_variables
you get an _
in the list. The _
provides a way to access the last return value in case it's lost forever.
You can access the return value of the previous line by using _
in your irb sessions.
x = 5
y = _
puts x
puts y
Running this through irb you get 5
logged two times. That is because _
stores the last return value, which is the assignment of 5 to the variable x.
Top comments (0)