Scripts in ruby a la python’s __name__ == ‘__main__’ idiom

A common idiom in python is to check the special variable __name__ to see if the current module is being run as a script or not. For example:

class Foo:
    ...

def bar():
    ...

if __name__ == '__main__':
    bar()

Here, if the module is run as a script (ie passed directly to the python interpreter), then __name__ has the value “__main__”, this is detected, and (in this case) the bar() function is called. On the other hand, if the module is just imported from some module, __name__ has a different value (the name of the module file, I think?), and bar() doesn’t get called.

This is nice for a number of reasons – for example, you might put unit tests into bar().

How to do this in Ruby? It’s not in FAQ, which surprised me. I was about to ask on ruby-talk but then remembered the biggest FAQ of them all, and turned to google. Aha (and eek, what a horrible mailing list interface). Anyway, it’s:

if __FILE__ == $0
    bar()
end

OK, so why does this work?

$0 contains the name of the script being executed – ie, the name of the file that was passed to the interpreter. Whatever code you’re executing, this value never changes over a particular run of ruby. On the other hand, __FILE__ is always the name of the current source file. If the two match, then the current source file is the one that was passed to the interpreter.

I guess that’s pretty clear. Cool.

5 Responses to “Scripts in ruby a la python’s __name__ == ‘__main__’ idiom”

  1. May 10th, 2006 | 10:02 pm

    Ah, cool – I’ve been wondering about this for a few weeks. Thanks!

  2. August 19th, 2007 | 12:32 pm

    Thanks! This is exactly what I was looking for, and the name of the article made it very easy to find on Google.

  3. April 24th, 2008 | 10:00 am

    Hi,
    When I create a new ‘ruby file’ in eclipse with RDT this is what is in the file by default. As a n00b to ruby I wondered what it did.

    if __FILE__ == $0
    # TODO Generated stub
    end

    Mick

  4. Ron
    May 8th, 2011 | 2:11 pm

    Great, thankyou

  5. Lu
    April 23rd, 2012 | 9:26 pm

    Awesome!
    Thanks a huge lot !!

    S@lu²