If $PROGRAM_NAME == __FILE__ Debugging

" if $PROGRAM_NAME == FILE " was mentioned briefly in the Debugging/Writing Testable Code section of the alpha course as the common trick to debugging, but I am still confused by how it operates. Could someone explain further? Thanks! The text and example code from alpha are:

“The solution is the trick if $PROGRAM_NAME == FILE. This checks to see if the currently running program ($PROGRAM_NAME) is the same as the current file (primes.rb). If so, then the current file is being invoked as a script, so we should kick things off. Otherwise, we’re loading it as part of some other program (like irb or Pry - we’ll get to these soon), and we shouldn’t do more than load the method definitions so that someone else may use them.”


def prime?(num)
(1…num).each do |idx|
if num % idx == 0
return false

def primes(num_primes)
ps = []
num = 1
while ps.count < num_primes
primes << num if prime?(num)

puts primes(100)

$PROGRAM_NAME is a global variable. It points to the argument (program name) we type after we type ‘ruby’ in the terminal.

File is the actual file we are currently in.
When we write if $PROGRAM_NAME == FILE we are comparing the two. If they are equal execute whatever code we put beneath it.

This is very helpful for debugging and being able to quickly execute code that we’ve written from the command line. Additionally, when we start breaking our code out over multiple files, it gives us the ability to write test code that will only execute if we run that file specifically but will not run when that file is being imported/required by another file.

So, from the example above, if we write ruby primes.rb it would execute the code beneath if $PROGRAM_NAME == FILE. But, if we had a file named math.rb that required primes.rb, when we type ruby math.rb that same code beneath the if statement from primes.rb would not execute.

A great, easy to do, exercise would be to drop a debugger into you code and actually type in $PROGRAM_NAME and __FILE__ to see what they are. Don’t be afraid to use the debugger to help you understand what all these variables are/do.

1 Like