What is “main” in Ruby?

2019-01-03 03:41发布

问题:

If I run this file as "ruby x.rb":

class X
end
x = X.new

What is the thing that is calling "X.new"?

Is it an object/process/etc?

回答1:

Everything in Ruby occurs in the context of some object. The object at the top level is called "main". It's basically an instance of Object with the special property that any methods defined there are added as instance methods of Object (so they're available everywhere).

So we can make a script consisting entirely of:

puts object_id
@a = 'Look, I have instance variables!'
puts @a

and it will print "105640" and "Look, I have instance variables!".

It's not something you generally need to concern yourself with, but it is there.



回答2:

The top-level caller is an object main, which is of class Object.

Try this ruby program:

p self
p self.class


回答3:

It's the X class. You're invoking the method "new" that creates an object of class X. So, if you run this text as a script, Ruby:

  • creates a new class X which is a subclass of Object, and which automatically (as a subclass of Object) inherits some methods, of which new is one.
  • sets up a name x
  • calls the new method on that new class X, creating an X instance object; x gets a reference to that object.


回答4:

It's the ruby interpreter running the line

x = X.new

As with many scripting languages, the script is interpreted from top to bottom rather than having a standard entry point method like most compiled languages.



回答5:

As Charlie Martin said, X.new is a call to the constructor on the X class, which returns an object of type X, stored in variable x.

Based on your title, I think you're looking for a bit more. Ruby has no need for a main, it executes code in the order that it sees it. So dependencies must be included before they are called.

So your main is any procedural-style code that is written outside of a class or module definition.



标签: