`if __name__ == '__main __' 'Ruby equivalent

I am new to Ruby. I want to import functions from a module that contains a tool that I want to continue to use separately. In Python, I would just do this:

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

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

+83
python ruby main
Feb 12 '10 at 2:30
source share
2 answers

From the Ruby I've seen in the wild (provided, not a ton), this is not a standard Ruby design template. Modules and scripts should remain separate, so I wonโ€™t be surprised if there is no good and clean way to do this.

EDIT: Found.

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

But it is definitely not often.

+109
Feb 12 '10 at 2:36
source share

If the stack trace is empty, we can start execution right and left. I do not know if it has been used traditionally or unconventionally since I have been in 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" 

Using:

 $ ./shmest.rb Test Shmest $ ./test.rb Main script Test 
+8
Oct 14 '13 at 22:55
source share



All Articles