If i put the following code:
a = 42
p TOPLEVEL_BINDING.local_variable_defined?(:a)
in a file "rubyScratch.rb" and ruby it using
ruby rubyScratch.rb
I get
true
However in irb I get
2.3.1 :001 > a = 42
=> 42
2.3.1 :002 > TOPLEVEL_BINDING.local_variable_defined?(:a)
=> false
Why is there this difference?
This is because the irb command (on my system, anyways) runs a small ruby script that looks like this:
#!/usr/bin/env ruby
#
# irb.rb - interactive ruby
# $Release Version: 0.9.6 $
# $Revision: 40560 $
# by Keiju ISHITSUKA([email protected])
#
require "irb"
IRB.start(__FILE__)
So, the TOPLEVEL_BINDING
is this script and not your IRB context.
While looking for some more information, I ran across this short article which states:
It is, as its name suggest, the Binding of your script's main scope:
a = 42 p binding.local_variable_defined?(:a) # => true p TOPLEVEL_BINDING.local_variable_defined?(:a) # => true def example_method p binding.local_variable_defined?(:a) # => false p TOPLEVEL_BINDING.local_variable_defined?(:a) # => true end example_method
To summarize, the TOPLEVEL_BINDING
is the binding
for the first script in the current context that was run by the Ruby VM. When running IRB, that script is the one that starts the IRB session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With