0

I have a following lines in my ruby script. It gives the output as main when i run this script. But i cannot access that main. I don't know what is this?

Is an object or instance?

For example :

puts self #=>  main

If i access the "main" means it gives the error like "undefined local variable or method".

Previously i use this self to print its current object within a class. For example:

class Ex
  puts self #=> Ex
end

Here, i can use that self object to get the current class name. After this i can able to access that Ex class. But in first example it returns main. But i can't access that. So what is a reason behind this?

Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37
SSS
  • 37
  • 6

2 Answers2

1

The keyword self in Ruby gives you access to the current object. In your cause, the Ex happens to be a class, not the instance of Ex. However, all the statements are being executed under the main object of ruby, as main happens to be the outer most object). For now the statement is inside the object main, meaning main is the inner most object. Therefore puts self is printing main as output.

for more information study:

https://www.jimmycuadra.com/posts/self-in-ruby/

krazedkrish
  • 638
  • 3
  • 10
1

Short answer:

Main is the special object, with special properties.

More information:

You touched theme called Introspection. What information wikipedia gives about it:

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime.

So what you are doing is calling introspection.

So lets move further, what we can do with this?

puts self.class

This will give Object. So next important thing is:

Everything in Ruby occurs in the context of some object.

So there is nice answer which disclose this.

Community
  • 1
  • 1
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37