Comparison __FILE__ and $0

Asked

Viewed 55 times

0

I recently saw this decision-making in a ruby code:

if __FILE__ == $0

    ....

So I had it printed out __FILE__ and $0 separately in irb and saw that the two pass the same information, my doubts are:

  • Why (when) make this comparison?
  • Why not compare with the same command (__FILE__ == __FILE__)?
  • Have some method to get the file name directly by __FILE__ without having to filter?

1 answer

1


In the ruby-lang.org has a good explanation of what/why. See:

__ FILE__ is the magic variable that contains the current file name. $0 is the name of the file used to start the program. Basically it checks "If this is the main file being used ..." This allows a file is used as a library, not to execute the code in this context, but if the file is being used as a executable, execute this code.

See more details here in this article.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.