How to specify a file path using '~' in Ruby?

前端 未结 2 1971
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 13:19

If I do:

require \'inifile\'

# read an existing file
file = IniFile.load(\'~/.config\')
data = file[\'profile\'] # error here

puts data[\'region\']
         


        
2条回答
  •  灰色年华
    2021-01-20 14:14

    When given ~ in a path at the command line, the shell converts ~ to the user's home directory. Ruby doesn't do that.

    You could replace ~ using something like:

    '~/.config'.sub('~', ENV['HOME'])
    => "/Users/ttm/.config"
    

    or just reference the file as:

    File.join(ENV['HOME'], '.config')
    => "/Users/ttm/.config"
    

    or:

    File.realpath('.config', ENV['HOME'])
    => "/Users/ttm/.config"
    

提交回复
热议问题