Jilani Khaldi <jilanik / tin.it> writes:

> So I see there is no "main" function to "init" the program in Ruby.

Aleksi Niemel<aleksi.niemela / cinnober.com> writes:

> When you execute the interpreter by saying something like
> 
>   ruby file_to_execute.rb
> 
> it starts to execute Ruby code in the file. In this case it first executes
> the class definition and then the "invisible main".

Ruby has an execution model which will seem strange coming from C++.

Unlike static languages such as 'C', Ruby executes everything. In C,

   struct { ... }

is a definition. In Ruby

   class ...

   end

is executable code -- it's actually running the class definition. This 
means you can do interesting things. For example, you could change the
to_s method used by a class from a verbose one to a restrained
one. Using conventional thinking, you'd do something like:

  class Fred

     def to_s
       if $VERBOSE
         # ... return large string
       else
         # ... return compact string
     end
  end

The 'if' statement is executed every time you call to_s.

However, if you know that $VERBOSE isn't going to change over the life 
of the program, in Ruby you can do:

  class Fred

    if $VERBOSE
      def to_s
        return 'long................string'
      end
    else
      def to_s
        return 'shortstring'
      end
    end
  end

You actually define one of two different methods depending on the
flag. The 'if' is only executed once.


> So actually the main in Ruby is a little bit like in Java. If you write
> something to top-level it gets executed, but usually it's better to write

I thought Java looked for a 'static void final main(String args[])' in 
a class of the same name as the class given to the interpreter, but
it's been a while (thankfully).


> if __FILE__ == $0
>    # the contents of main
> end

This idiom is not required at all for normal Ruby programs. It's a
trick used by library routine writers that want to include their own
test code in the same file as the library.

If they are included as a library, $0 (the name of the program that's
running) won't be the same as __FILE__, the name of the library
file. The code won't then get executed.

However, run the library as a standalone program, and the two match,
so the test code gets executed.

You don't need this idiom for normal programs.

> There should be the better way (tm). Show me the light.

Don't use it! Seriously - you normally don't have to.

If you don't like it and you _do_ need some kind of self test
capability, you could always do it other ways. For example, create a
library called SelfTest.rb, which contains

   $SelfTest = true


In your other libraries, have

   if $SelfTest
     # code to perform test
   end

Then, to enable the self test, use:


  ruby -r SelfTest  mylibrary.rb


However, __FILE__ == $0 is pretty much an idiom, and people are pretty 
much used to it by now.


Regards


Dave