If `main` is an instance of` Object`, why can't I name it?

When I type self , I get the return value of main . I did this test:

 main2 = Object.new 

Then I can call main2 , and it returns something, but when I call main , it causes an undefined variable error. How does this happen?

Here's an assumption I found on another site about how this top-level environment works:

 class Object Object.new.instance_eval do def self.to_s "main" end private ## # Your program gets inserted here... ## end end 

That makes sense to me.

+7
source share
3 answers

β€œ What is Ruby Top Level? This is a Ruby Top Level article that explains everything you need to know.

However, unlike you, you can access main anywhere in your program using TOPLEVEL_BINDING.eval('self') .

+14
source

Evaluating self in irb returns an object that prints as primary. Here is a transcript that should help:

 $ irb >> self => main >> main NameError: undefined local variable or method `main' for main:Object from (irb):2 >> self.inspect => "main" >> self.class >> Object 

When you enter main in irb, it tries to evaluate the variable main , which is not declared.

+4
source

You cannot directly reference the main object to something like

 myvar = main 

It is impossible to call him by his "name". However, you can capture it in a variable called main, similar to this

 main = self puts main # => main 

" top-level object? top-level methods? " - useful reference information on the main object of the inventor of Ruby.

+1
source

All Articles