What is __FILE__ and $0? (newbie question)

O

Omar Campos

Hello everyone,

I am new to Ruby, learning the basics, and the basics of FXRuby (I
know this is not the FXRuby forum, but I think this question pertains
Ruby per se). I've noticed the "recommended" way of creating the main
app loop goes like this:

if __FILE__ == $0
#main loop code
end

I've already done some GUI apps, and had no need of these wierd
variables. But I am still curious, what do they mean?

Thanks for any info!
 
O

Omar Campos

Hi,

Thanks for your answer. I just wanted to understand a little better
what it meant. I don't like to include mystery code in my programs,
simply because someone says it works and because "you always need to
include that". I couldn't find these variables in the Ruby Book
included with the windows 1.8 distribution, and typing puts __FILE__ on
the interactive ruby console didn't print anything useful (which now
makes perfect sense!).

Once more, thanks.
 
R

Rob Biedenharn

Hi,

Thanks for your answer. I just wanted to understand a little better
what it meant. I don't like to include mystery code in my programs,
simply because someone says it works and because "you always need to
include that". I couldn't find these variables in the Ruby Book
included with the windows 1.8 distribution, and typing puts __FILE__
on
the interactive ruby console didn't print anything useful (which now
makes perfect sense!).

Once more, thanks.


That idiom is typically used to include test code within a file that
is normally used as a library. The guarded code is run when:
ruby foo.rb
but not when bar.rb contains
require 'foo'
as others have pointed out.

Now you should have a "why" to go with your "what" and "how" ;-)

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 

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

No members online now.

Forum statistics

Threads
473,795
Messages
2,569,644
Members
45,356
Latest member
deepthi.kodakandla

Latest Threads

Top