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

前端 未结 2 1972
佛祖请我去吃肉
佛祖请我去吃肉 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 13:56

    Ruby has a method for this case. It is File::expand_path.

    Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a “~”, which expands to the process owner’s home directory (the environment variable HOME must be set correctly). “~user” expands to the named user’s home directory.

    require 'inifile'
    
    # read an existing file
    file = IniFile.load(File.expand_path('~/.config'))
    

提交回复
热议问题