It seems there's no main function in Ruby. So what's the equivalent for main in Ruby?
Asked
Active
Viewed 1,410 times
2
-
2The entire script is executed from beginning to end in the top-level environment. – matt Mar 24 '13 at 02:48
-
2The thing to remember is that every line of Ruby code is executable, including class declarations and method definitions. It is all actually executed as it is encountered. – matt Mar 24 '13 at 02:55
-
Possible duplicate: http://stackoverflow.com/questions/9687106/is-there-a-main-method-in-ruby-like-in-c – Josh Mar 24 '13 at 02:59
1 Answers
6
There is no such thing in Ruby. The interpreter executes code from top to bottom so your main script is implicitly the body of "main". For example, suppose you have two files script_a.rb
and script_b.rb
. And suppose the contents of script_a.rb
is as follows:
require_relative './script_b'
puts 1 + 1
Now if you run ruby script_a.rb
what you will get in terms of actual code execution will be as follows: Find script_b.rb
, execute the contents of script_b.rb
, execute puts 1 + 1
.

David K.
- 6,153
- 10
- 47
- 78
-
1Interestingly, there is a `main` object in Ruby which you can find by opening IRB and asking it for `self`. It's a [top-level object](https://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/) which serves as the context for all other objects. Great answer on this: http://stackoverflow.com/a/917842/1042144 – Brian Kung Mar 24 '13 at 03:03