How to list local-variables in Ruby?
Asked Answered
S

3

33
def method
  a = 3
  b = 4

  some_method_that_gives # [a, b] 
end
Saad answered 20/12, 2010 at 6:10 Comment(0)
J
50

local_variables

It outputs array of symbols, presenting variables. In your case: [:a, :b]

Jitterbug answered 20/12, 2010 at 6:17 Comment(2)
Can't believe I didn't find it before. Thanks!Saad
Some versions of Ruby output an array of strings instead of an array of symbols. Ruby 2.0 and 1.9 use symbols, but Ruby 1.8.7 used strings.Weeden
S
7

local_variables lists local variables but it lists them before they are defined. See this:

p local_variables
a = 1
p local_variables

this outputs

[:a]
[:a]

which may not be what you expect. Contrast with defined?

p defined? a
a = 1
p defined? a

which outputs the more anticipated

nil
"local-variable"
Sparrowgrass answered 15/2, 2014 at 17:12 Comment(0)
A
1

if you're looking for the list with their values:

variables = self.local_variables.each_with_object({}) { |key, hash| hash[key] = binding.local_variable_get(key) }
Allelomorph answered 8/4, 2021 at 18:48 Comment(1)
To avoid using eval you can use Binding#local_variable_get instead. I modified you solution like this: local_variables.each_with_object({}) { |key, hash| hash[key] = binding.local_variable_get(key) }Lento

© 2022 - 2024 — McMap. All rights reserved.