Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use 'if __FILE__ == $PROGRAM_NAME'

Tags:

ruby

I see many programs being encased by the following if statement:

if __FILE__ == $PROGRAM_NAME
  # rest of the program
end

I read that it is "to make sure that the current file corresponds to the program that needs to [be] executed".

When should I use this statement in my programs? In what situations should I use this? And when is it not necessary?

like image 549
C. Ball Avatar asked May 11 '26 22:05

C. Ball


2 Answers

when is it not necessary?

Almost always.

when should I use this statement in my programs?

When you have a file that is mainly used by other files, but sometimes you want to run the file directly. In this case, this section of the code normally carries some tests or example usage.

# animal.rb
class Animal
  def voice
    raise NotImplementedError
  end
end

class Dog < Animal
  def voice
    'Woof!'
  end
end


if __FILE__ == $PROGRAM_NAME
  puts "testing voice"
  puts Dog.new.voice == 'Woof!'
end

If you run ruby animal.rb, you'll see the debug/testing output. If you just require 'animal' from another file, you won't.

like image 79
Sergio Tulentsev Avatar answered May 13 '26 12:05

Sergio Tulentsev


When the code is called from another Ruby program as a library, that condition does not hold. When it is the main program that is executed, that condition holds.

Sometimes, you want to program software that can either be used as a library or run as a main program, and want to make it behave differently accordingly. In such case, you use it.

like image 20
sawa Avatar answered May 13 '26 11:05

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!