From f9f19aefddcbe8cf2419707a48d4c782cf354cfe Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 25 Jul 2015 22:05:58 -0500 Subject: [PATCH] Add Listing Local Variables as a ruby til. --- README.md | 1 + ruby/listing-local-variables.md | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 ruby/listing-local-variables.md diff --git a/README.md b/README.md index 0bb7783..9ff2776 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [FactoryGirl Sequences](ruby/factory-girl-sequences.md) - [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md) - [Limit Split](ruby/limit-split.md) +- [Listing Local Variables](ruby/listing-local-variables.md) - [Override The Initial Sequence Value](ruby/override-the-initial-sequence-value.md) - [Parallel Bundle Install](ruby/parallel-bundle-install.md) - [Percent Notation](ruby/percent-notation.md) diff --git a/ruby/listing-local-variables.md b/ruby/listing-local-variables.md new file mode 100644 index 0000000..ae54650 --- /dev/null +++ b/ruby/listing-local-variables.md @@ -0,0 +1,30 @@ +# 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. + +```ruby +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 + +```ruby +[:x, :z] +[:a, :x, :z] +[:a, :x, :z] +[:x, :z] +=> 4 +``` + +[source](http://ruby-doc.org/core-2.2.0/Binding.html#method-i-local_variables)