Short Tutorial on Ruby-Lang says the following:
if __FILE__ == $0
__FILE__ is the magic variable that contains the name of the current file. $0 is the name of the file used to start the program. This check says “If this is the main file being used…”
This allows a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code.
But the bold lines above are not clear, since I am new to Ruby.
__FILE__ returns the name of the current file. $0 returns the name of the script currently being executed.
Imagine you have this file
# foo.rb
if __FILE__ == $0
puts 'foo'
else
puts 'bar'
end
and you run ruby foo.rb from the command line then it will output foo because both – __FILE__ and $0 – return "foo.rb".
But if you have the same foo.rb file and require it in another bar.rb file like this
# bar.rb
require 'foo'
and you run the other file ruby bar.rb then the script will print bar because __FILE__ would still return "foo.rb" but $0 would now return "bar.rb".
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