How to know or get main
, mean top-level binding, object evaluated in Ruby?
$ irb
irb(main):001:0> self
=> main
irb(main):002:0> eval "self"
=> main
irb(main):003:0> eval "main"
NameError: undefined local variable or method `main' for main:Object
from (irb):3:in `eval'
from (irb):3:in `eval'
from (irb):3
from /home/malo/.rvm/rubies/ruby-1.9.3-p448/bin/irb:12:in `<main>'
The main constraint is that the code word shell be evaluated from anywhere, from within a class, module or instance. So it shall be universal.
To gain access to the "main" object from anywhere, use the TOPLEVEL_BINDING
:
class MyShell
def main_object
TOPLEVEL_BINDING.eval('self') #=> "main"
end
end