DEV Community

Ahmad khattab
Ahmad khattab

Posted on

5 3

Discoveries in Ruby(and Rails): List local/global_variables in the current scope, and the (_) in irb sessions.

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Resources

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay