Kernel#local_variables
local_variables -> [symbol] Returns:
Array · Updated March 13, 2026 · Kernel Methods variables introspection scope debugging
The local_variables method returns an array of all local variable names defined in the current scope. It’s useful for debugging, metaprogramming, and understanding variable scope.
Basic Usage
# In current scope
name = "Alice"
age = 30
city = "NYC"
puts local_variables # => [:name, :age, :city]
Practical Examples
Debugging
def inspect_locals
puts "Local variables: #{local_variables.inspect}"
end
name = "test"
inspect_locals # Shows: [:name]
Dynamic Variable Handling
# Set variables dynamically
local_variables.each do |var|
value = binding.local_variable_get(var)
puts "#{var} = #{value}"
end
Scope Inspection
x = 1
y = 2
def method_with_own_scope
z = 3
puts local_variables # Only shows :z
end
method_with_own_scope
puts local_variables # Shows :x, :y
Variable Capture
def capture_variables
captured = {}
local_variables.each do |var|
captured[var] = binding.local_variable_get(var)
end
captured
end
name = "Alice"
age = 30
capture_variables # => {:name=>"Alice", :age=>30}
Within Blocks
# Blocks create new scope for local variables
x = 10
local_variables # => [:x]
3.times do |i|
y = i
end
# y not visible here (different scope)
puts local_variables # => [:x]
Conditional Variables
if false
secret = "hidden"
end
puts local_variables # [:secret] - variable exists but is nil!
Debugging Helpers
def debug_locals
local_variables.each do |var|
value = binding.local_variable_get(var)
puts "#{var.inspect}: #{value.inspect}"
end
end
Binding Integration
# Use with Binding objects
b = binding
x = 5
puts b.local_variables # => [:x]
# From other scopes
def get_binding
local_var = "hello"
binding
end
b = get_binding
puts b.local_variables # => [:local_var]
Common Use Cases
- Debugging variable states
- Building REPL tools
- Serializing scope
- Dynamic method creation
- Template engines