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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With