Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I define a main method in my ruby scripts?

People also ask

Do you need a main method in Ruby?

@Hauleth's answer is correct: there is no main method or structure in Ruby.

Is there a main in Ruby?

The Ice::Application Class in Ruby. You may also call main with an optional file name or an InitializationData structure. If you pass a configuration file name to main , the settings in this file are overridden by settings in a file identified by the ICE_CONFIG environment variable (if defined).

How do you define a function in Ruby?

Functions in Ruby are created using the def keyword (short for define). Functions that exist in an object are typically called methods. Functions and methods are the same, except one belongs to an object.


I usually use

if __FILE__ == $0
  x = SweetClass.new(ARGV)
  x.run # or go, or whatever
end

So yes, you can. It just depends on what you are doing.


I've always found $PROGRAM_NAME more readable than using $0. Half the time that I see the "Perl-like" globals like that, I have to go look them up.


if __FILE__ == $PROGRAM_NAME
  # Put "main" code here
end

You should put library code in lib/ and executables, which require library code, in bin/. This has the additional advantage of being compatible with RubyGems's packaging method.

A common pattern is lib/application.rb (or preferably a name that is more appropriate for your domain) and bin/application, which contains:

require 'application'
Application.run(ARGV)

My personal rule of thumb is: the moment

if __FILE__ == $0
    <some code>
end

gets longer than 5 lines, I extract it to main function. This holds true for both Python and Ruby code. Without that code just looks poorly structured.