What does `if __FILE__ == $0` mean in Ruby

前端 未结 6 566
挽巷
挽巷 2020-12-07 20:37
if __FILE__ == $0
  $:.unshift File.join(File.dirname(__FILE__),\'..\')

I found this code in Ruby, what\'s the meaning?

6条回答
  •  不思量自难忘°
    2020-12-07 21:22

    A great explanation on what/why from ruby-lang.org:

    __FILE__ is the magic variable that contains the name of the current file. $0 is the name of the file used to start the program. This check says “If this is the main file being used…” This allows a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code.

    See: https://www.ruby-lang.org/en/documentation/quickstart/4/

提交回复
热议问题