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”
Leave a reply
You can use HTML, but you don't have to. Formatting tips (for code, quotes, etc.) here.
Ah, cool – I’ve been wondering about this for a few weeks. Thanks!
Thanks! This is exactly what I was looking for, and the name of the article made it very easy to find on Google.
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
Great, thankyou
Awesome!
Thanks a huge lot !!
S@lu²