Today I Learned

hashrocket A Hashrocket project

Listing Local Variables

In Ruby 2.2, the binding object gives us access to a method #local_variables which returns the symbol names of the binding's local variables. We can see this in action with

def square(x)
  puts binding.local_variables.inspect
  x.times do |a|
    puts binding.local_variables.inspect
  end
  z = x * x
  puts binding.local_variables.inspect
  z
end
square(2)

which results in

[:x, :z]
[:a, :x, :z]
[:a, :x, :z]
[:x, :z]
=> 4

source

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.