Checking if a Ruby program was executed or imported via require

command-line, ruby

Solution

Change foo.rb to read:

if __FILE__ == $0
  puts "Hello"
end

That checks `__FILE__` - the name of the current ruby file - against `$0` - the name of the script which is running.

Problem

How do you check if a Ruby file was imported via "require" or "load" and not simply executed from the command line? For example: Contents of foo.rb: ``` puts "Hello" ``` Contents of bar.rb ``` require 'foo' ``` Output: ``` $ ./foo.rb Hello $ ./bar.rb Hello ``` Basically, I'd like calling bar.rb to not execute the puts call.

Original source

Related problems