Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of __FILE__ = $0 as given on ruby-lang.org

Tags:

ruby

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.

like image 656
Sahil Babbar Avatar asked Nov 23 '25 07:11

Sahil Babbar


1 Answers

__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".

like image 71
spickermann Avatar answered Nov 28 '25 15:11

spickermann