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

前端 未结 4 811
遇见更好的自我
遇见更好的自我 2021-02-04 22:53

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

4条回答
  •  灰色年华
    2021-02-04 23:33

    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.

提交回复
热议问题