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

前端 未结 6 575
挽巷
挽巷 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:26

    I recommend you use $PROGRAM_NAME alias over $0 since it’s a little clearer what you mean when you use it—they mean the same thing.

    Now, what does $PROGRAM_NAME/$0 mean? From the Ruby docs:

    $0
    Contains the name of the script being executed. May be assignable.

    Let’s demonstrate how this works with code.

    1. Create hello.rb

    module Hello
      def self.world
        puts "Hello, world!"
        puts "$0       = #{$0}"
        puts "__FILE__ = #{__FILE__}"
      end
    end
    
    if $PROGRAM_NAME == __FILE__
      puts Hello.world
    end
    

    Look what happens if you run this file by itself:

    $ ruby hello.rb
    Hello, world!
    $0       = hello.rb
    __FILE__ = hello.rb
    

    2. Create a Rakefile

    require 'rake'
    require_relative 'hello'
    
    task :hello do
      Hello.world
    end
    

    Now execute this same code from within the context of a Rake task:

    $ rake hello
    Hello, world!
    $0       = /Users/sean/.rbenv/versions/2.3.0/bin/rake
    __FILE__ = /Users/sean/Projects/hello/hello.rb
    

    Wrapping code at the end of a Ruby file in a if $PROGRAM_NAME == __FILE__ conditional is an idiom many developers use to say “only execute this code if you’re running this file individually”.

    What kind of code would you wrap in this conditional? I often use it to demonstrate how to use a module. This also makes it very convenient to execute this file in isolation to make sure it works outside the context of the larger program you may be writing.

    If you didn’t wrap your example code in this conditional, then it would get executed whenever the file is required/loaded in the lifecycle of your larger program, which is almost certainly not what you want.

提交回复
热议问题