I have stumbled across this sintax while reviewing a code in Ruby. The code is:
if __FILE__ == $PROGRAM_NAME
#some code...
end
I suppose __FILE__ is a variable that gets me the name of the file I am in?
But what does $PROGRAM_NAME simbolize then? Also, why is this if statement necessary, since the program works with or without it?
__FILE__always returns the path of the source file. It's not a variable so you can't assign value to it. Whether it returns a relative path or an absolute one depends on how you run the script.$PROGRAM_NAMEor$0by default returns the command that boots the program (minus the path of ruby interpreter). For example, you have a script filetest.rblike this:If you run this script with
ruby test.rb, it printsIf you run the script with
ruby /path/to/test.rb, it printsIf you give the script an execution permission and run it with
./test.rb, it printsUnlike
__FILE__,$PROGRAM_NAMEand$0are real global variables, and you can change their values.$PROGRAM_NAMEand$0are aliases to each other, so you change the value of either one, the value of the other will change accordingly. For example, you have atest2.rblike this:it prints