30
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

__FILE__と$0の違い

Posted at

ググればいろんなところで解説されているけど、実際にコード書いて確かめてみた。

filename.rb
puts "__FILE__: #{__FILE__}"
puts "$0: #{$0}"
require_filename.rb
require_relative filename
% ruby filename.rb
__FILE__: filename.rb
$0: filename.rb
% ruby require_filename.rb
__FILE__: /Users/naoty/workspace/ruby/filename.rb
$0: require_filename.rb
  • __FILE__は実行中のプログラムのファイル名(リファレンスによると、フルパスとは限らないみたい)
  • $0は実行時に指定されたファイル名(相対パス)
  • 以下のようなコードを見かけるのだけど、相対パスと絶対パスで一致しない場合は考慮されていないような気がする。。。
if __FILE__ == $0
  # hogehoge
end
30
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?