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?
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?
It's the X class. You're naming the method "new" that creates and object of class X. So, if you run this text as a script, ruby
new
is one.x
new
method on that new class X
, creating an X object; x gets a reference to that object.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.
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.
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.
The top-level caller is an object main, which is of class Object.
Try this ruby program:
p self
p self.class