Top-level or main context

I’m having a terrible time wrapping my head around the concept of the main context(self).

Is it as simple as the context(self) has to start somewhere so the environment sets the main context(self) to an instance of Object(called main) with some one-off behaviour?

I think that’s basically it.

Ruby’s an OOP language, so everything has to live in some kind of object. If you started in a tabula rasa, what would it mean to define a variable or method? Where would it live? What methods can you call?

So the ‘main’ context provides a ‘self’ into which you can put definitions and access basic methods, like puts:

> self.class
 => Object 
> self.class.ancestors
 => [Object, Kernel, BasicObject]
> Kernel.methods.sort
[:!, :!=, :!~, :<, :<=, :<=>,
 # ...
 puts,
# ...
]

And you can check up on local variables:

> self.local_variables
 => [:_] 
> x = 3
 => 3 
> self.local_variables
 => [:x, :_] 

@pcl
Thanks for confirming what I thought.

I love Ruby but have zero experience in languages like SmallTalk so I have to really stop and think when I have to understand why Ruby does things the way it does.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs