Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`if __name__ == '__main__'` equivalent in Ruby

Tags:

python

main

ruby

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?

like image 221
Imagist Avatar asked Feb 12 '10 02:02

Imagist


2 Answers

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.

like image 139
Matchu Avatar answered Oct 01 '22 02:10

Matchu


If stack trace is empty, we can start executing to the right and left. I don't know if that's used conventionally or unconventionally since I'm into Ruby for about a week.

if caller.length == 0   # do stuff end 

Proof of concept:

file: test.rb

#!/usr/bin/ruby                                                                   if caller.length == 0   puts "Main script" end  puts "Test" 

file: shmest.rb

#!/usr/bin/ruby -I .                                                              require 'test.rb'  puts "Shmest" 

Usage:

$ ./shmest.rb  Test Shmest  $ ./test.rb Main script Test 
like image 27
uKolka Avatar answered Oct 01 '22 03:10

uKolka