What is __FILE__ and $0? (newbie question)

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!

On Monday 23 November 2009 07:18:12 pm Omar C. wrote:

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?

I’m not sure that would always work…

$0 is probably named after the same variable in the shell – it tells
you how
the current program was executed.

FILE is the name of the current file, wherever it’s accessed.

It seems that what they’re trying to do is only run the main loop when
your
program is run as a program, and not when it’s used as a library. That
is, if
your program is foo.rb, and you run it as foo.rb, FILE will be
‘foo.rb’,
and $0 will also be ‘foo.rb’, so the main loop will run. But if you then
write
a program called bar.rb, which requires foo, $0 will be ‘bar.rb’, but
FILE
will still be ‘foo.rb’, so the main loop will not run.

I’m not sure why I’d ever want to do that, but there you go.

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.

This is a Google-type question

eg http://forgottenlink1.blogspot.com/2007/09/ruby-file.html

On Nov 23, 2009, at 9:58 PM, Omar C. wrote:

Once more, thanks.

Posted via http://www.ruby-forum.com/.

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” :wink:

-Rob

Rob B. http://agileconsultingllc.com
[email protected]