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

前端 未结 4 807
遇见更好的自我
遇见更好的自我 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:50

    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
    

提交回复
热议问题