Hello Julian,
Not sure I’m able to explain this “Trick”
But, I’m going to try my best to explain it my way of understanding the trick.
#In bash:
indent preformatted text by 4 spaces
if you haven't run any bash file, and just open the terminal and type "echo $0"
--> -bash # which tells us that you haven't run any bash shell script
However, if you run a bash script file, $0 will change to the file name that is being executed.
#In Java (main method):
Hello.java
public Hello{
public static void main(String[] args){ ...}
}
args is an array of strings which contains the arguments from the command line
For example:
In the terminal:
javac Hello.java # --> Hello.class
java Hello name1 name2 other
Then, args[0] = “name1”, args[1] = “name2”, args[2] = “other”
In Python:
#hello.py
print "hello world"
In the terminal, run python in interactive mode:
python -i hello.py
>>> import sys
>>> sys.argv[0]
>>> 'hello.py'
So argv[0] here is the file name “hello.py”
#In Ruby:
From ruby doc $0, and FILE
"
$0
Contains the name of the script being executed. May be assignable.
"
__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.
In ruby, $PROGRAM_NAME and $0 are the same variable, they’re global variables.
- $PROGRAM_NAME or $0 is the name of file that is being executed.
-
FILE_ is the name of the current file or program (source file, library, debugger)
Example:
# hello.rb
def hello
puts "Hello World"
end
if __FILE__ == $PROGRAM_NAME
hello
end
In the terminal:
run “ruby hello.rb”
indent preformatted text by 4 spaces
>>> ruby hello.rb
>>> Hello World
In this case FILE is the same as $PROGRAM_NAME (which is true) , then your program will executed the block that is between “if FILE__ == $PROGRAM_NAME” and “end”, it prints “Hello World”
Different case:
# hello.rb
require 'byebug'
def hello
puts "Hello World"
end
if __FILE__ == $PROGRAM_NAME
byebug
hello
end
in the terminal, run “ruby hello.rb” , you will be in the debugging mode “byebug”
***** We are in the debugging mode *****
>>> __FILE__
>>> "(byebug)"
>>> $0
>>> "hello.rb"
>>> $PROGRAM_NAME
>>> "hello.rb"
>>> $PROGRAM_NAME == $0
>>> true
>>> $PROGRAM_NAME == __FILE__
>>> false
In this case, $PROGRAM_NAME == FILE_ is false because the current source/program we are running is byebug( FILE_ ). So, we’re in the debugging mode “byebug”, it allows us to execute “hello.rb” isolated with byebug.
I usually treat
if _FILE__ == $PROGRAM_NAME
end
as my main method. If I want to run my program, create class object, invoke a method, and prints stuff, I will put it there (main method)
I hope it helps 