Can a Ruby script tell what directory it’s in?

倖福魔咒の 提交于 2019-12-22 01:55:14

问题


Inspired by "Getting the source directory of a Bash script from within", what's the Ruby way to do this?


回答1:


For older versions of Ruby (< 2.0), the script being run can be found using:

  • File.dirname(__FILE__) - relative path; or
  • File.expand_path(File.dirname(__FILE__)) - the absolute path.

For newer versions of Ruby, try:

  • __dir__

Using __dir__ will return the script path even after a call to Dir.chdir; whereas, using the older syntax may not return the path to the script.




回答2:


Use __dir__

As of Ruby 2.0, __dir__ is the simplest way to get this. It

Returns the canonicalized absolute path of the directory of the file from which this method is called.

See the __dir__ documentation, and "Why is __FILE__ uppercase and __dir__ lowercase?".




回答3:


use __dir__

File.dirname(__FILE__) is not a proper way to get directory where script is stored.

At start working directory and directory with script file is the same, but it may change.

For example:

Dir.chdir('..') do
    puts __dir__
    puts File.expand_path(File.dirname(__FILE__))
end

for script file stored in /Desktop/tmp running it will give output

/home/mateusz/Desktop/tmp
/home/mateusz/Desktop



回答4:


ENV["PWD"] seems the simplest way for me under Linux. I don't know of an OS-agnostic way.



来源:https://stackoverflow.com/questions/2206714/can-a-ruby-script-tell-what-directory-it-s-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!