I wanted a way to treat a Ruby file as both an importable library or a script. The best solution I could find was as follows:
if __FILE__ == $0 #script / run as self code goes here end
If the file is called directly a la ruby ./library.rb, the code within that if block will be executed. If included, __FILE__, the file that this code exists in will not match $0, the file being executed and the code in that block will not be executed.
PHRASE = "Hello World" def get_phrase PHRASE end if __FILE__ == $0 puts "Executing library.rb" puts get_phrase end
require "library.rb" puts "Executing script.rb" puts get_phrase
Running ruby script.rb will produce:
Executing script.rb Hello World
Running ruby library.rb will produce:
Executing library.rb Hello World
It seems trivial but I’ve utilized this several times while creating large collections of scripts.