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.