If __FILE__ == $Program name


#1

Hi there,

I have just started the Ruby final exercise and the first thing it asks is to type a runner code to start the program.

I was lost and looked at the solution offered, while it made my program run, i have never seen this before:
if FILE == $PROGRAM_NAME
my_list = List.new
puts “You have created a new list”
end

Could someone explain to me what the first line of code actually does? I understand that it is an if statement checking if the file equals the program name, but the purpose of __ & __ either side i am unclear on? and is PROGRAM NAME something in built to ruby?

Thanks in advance!


#2

That line checks if you’re executing that code directly. When programming, you often want to reuse or categorize stuff you write. You may for example want to use some function defined in some other file. In Ruby, you can use require and require_relative to use code in other files:

require_relative "my_functions_and_stuff.rb"
#More code here...

What it does is, it executes the code in the given file. So if you’ve defined some class in my_functions_and_stuff.rb, it can be used in the file that require_relatived it.
The problem is that not only function and variables definitions occur but also will anything else be executed:

#This is some file whose code should be reused.
def myFunc()
  return 3
end
puts "You probably don't want to see this printed to the screen..."

A way to avoid it is to write that check to see if it’s being required or directly launched:

def myFuc()
  return 3
end
if __FILE__ == $PROGRAM_NAME
  puts "This will only be printed when directly launched."
end

__FILE__ holds the file name in which the code is contained. $PROGRAM_NAME holds the name of the file which you executed.
This check is useful when you want to define stuff that should be able to be reused from other files but still interact with the user when executed.

Sorry about the repeated words in my post. I am in a bit of a hurry.