tags:

views:

390

answers:

1

I am new to Ruby. I'm looking to import functions from a module that contains a tool I want to continue using separately. In Python I would simply do this:

def a():
    ...
def b():
    ...
if __name__ == '__main__':
    a()
    b()

This allows me to run the program or import it as a module to use a() and/or b() separately. What's the equivalent paradigm in Ruby?

+9  A: 

From the Ruby I've seen out in the wild (granted, not a ton), this is not a standard Ruby design pattern. Modules and scripts are supposed to stay separate, so I wouldn't be surprised if there isn't really a good, clean way of doing this.

EDIT: Found it.

if __FILE__ == $0
    foo()
    bar()
end

But it's definitely not common.

Matchu
What's the reasoning behind keeping modules and scripts separate, out of curiosity?
Imagist
I think it's just what Rubyists prefer to do. A module definition is a module definition. If you want to take some action with that module, fine, but the action you're taking *isn't* a module definition.
Matchu
It's handy, though, for testing things -- you can put module tests in there and run them just from the module file without any wrapper.
ebneter
@Imagist and @ebneterOr the other way around: the script is a single module that is intended to be run from the commandline, but you also want to be able to test it in parts and have the test in a seperate module. In that case, __NAME__ == $0 is invaluable.
Confusion
I haven't seen this either, but it isn't frowned upon. The official Ruby docs use it: http://www.ruby-lang.org/en/documentation/quickstart/4/
Lewisham