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

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


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.


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 stuffend

Proof of concept:

file: test.rb

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

file: shmest.rb

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

Usage:

$ ./shmest.rb TestShmest$ ./test.rbMain scriptTest


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

is preferred by Rubocop over this:

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