Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is TOPLEVEL_BINDING in ruby?

Tags:

ruby

binding

It doesn't equal the binding at the main thread, what is this toplevel scope? What does this scope differ from the binding at the main thread?

> ruby -e 'puts TOPLEVEL_BINDING === binding'
false
like image 477
steveyang Avatar asked Jun 18 '13 13:06

steveyang


1 Answers

The fact is, TOPLEVEL_BINDING always refers to a predefined global instance of Binding, while Kernel#binding creates a new instance of Binding that encapsulates the current execution context every time. At top level, they both contain the same bindings, but they are not the same object and you cannot test their binding equality with == or ===.

puts TOPLEVEL_BINDING
puts TOPLEVEL_BINDING
puts binding
puts binding
puts binding == binding

# =>
#<Binding:0x9769ea0>
#<Binding:0x9769ea0>
#<Binding:0x9941ea8>
#<Binding:0x9941e58>
false
like image 85
Arie Xiao Avatar answered Sep 18 '22 22:09

Arie Xiao