如果我这样做:
require 'inifile'
# read an existing file
file = IniFile.load('~/.config')
data = file['profile'] # error here
puts data['region']
这里出现错误:
t.rb:6:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
如果我指定绝对路径,它就会消失:
file = IniFile.load('/User/demo1/.config')
但我不想对位置进行硬编码。如何将 ~
解析为 Ruby 中的路径?
最佳答案
对于这种情况,Ruby 有一个方法。是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’shome
directory.
require 'inifile'
# read an existing file
file = IniFile.load(File.expand_path('~/.config'))
关于ruby - 如何在 Ruby 中使用 '~' 指定文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28083413/