What does __FILE__ mean in Ruby?

前端 未结 4 1203
攒了一身酷
攒了一身酷 2020-11-28 00:43

I see this all the time in Ruby:

require File.dirname(__FILE__) + \"/../../config/environment\"  

What does __FILE__ mean?

4条回答
  •  心在旅途
    2020-11-28 01:15

    In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

    In PHP __FILE__ is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:

    File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")
    

    I should note that in Ruby 1.9.1 __FILE__ contains the full path to the file, the above description was for when I used Ruby 1.8.7.

    In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

提交回复
热议问题