Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TOPLEVEL_BINDING difference in irb and script

Tags:

ruby

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?

like image 813
Omar Khan Avatar asked Jan 28 '23 09:01

Omar Khan


1 Answers

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.

like image 115
Chris Hall Avatar answered Feb 08 '23 22:02

Chris Hall