Explanation of if __FILE__ == $0

P

PJ Hyett

So I've tracked this down:
__FILE__ is the name of the current source file
$0 at the top level is the name of the top-level program being executed

But I'm still confused as to what this if statement is accomplishing?
It's obviously useful for something since it's used quite often. Does
this pertain to when a script is called from another script?

Thanks,
PJ
 
D

Daniel Harple

So I've tracked this down:
__FILE__ is the name of the current source file
$0 at the top level is the name of the top-level program being
executed

But I'm still confused as to what this if statement is accomplishing?
It's obviously useful for something since it's used quite often. Does
this pertain to when a script is called from another script?

Thanks,
PJ

It is used when you want to run something when the file is executed
directly. Some put tests in their code like this, I think this is bad
form. Tests belong in a separate file.

File a.rb
---------
class Foo
end

if __FILE__ == $PROGRAM_NAME # [1]
puts "Testing out class Foo"
# ...
end

File b.rb
---------
require 'a'
puts "The if block in a.rb is not executed"

__END__

$ruby a.rb
Testing out class Foo
$ruby b.rb
The if block in a.rb is not executed

[1] $PROGRAM_NAME is the less cryptic name for $0

-- Daniel
 
J

Jim Freeze

if __FILE__ == $PROGRAM_NAME # [1]
[1] $PROGRAM_NAME is the less cryptic name for $0

Most definitely. I would like to see this changed in existing code.

Being a long time Ruby user, I always used $0 until
recently, Then I read some code by a new ruby user (whom I introduced
to ruby).
I never bothered to see if an alternative to $0 existed.

You can learn from anyone. Even the nubies. :)

Jim Freeze
 
P

PJ Hyett

Thanks guys, that's helpful.

-PJ

if __FILE__ =3D=3D $PROGRAM_NAME # [1]
[1] $PROGRAM_NAME is the less cryptic name for $0

Most definitely. I would like to see this changed in existing code.

Being a long time Ruby user, I always used $0 until
recently, Then I read some code by a new ruby user (whom I introduced
to ruby).
I never bothered to see if an alternative to $0 existed.

You can learn from anyone. Even the nubies. :)

Jim Freeze
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top