如果我做:
require 'inifile'
# read an existing file
file = IniFile.load('~/.config')
data = file['profile'] # error here
puts data['region']
Run Code Online (Sandbox Code Playgroud)
我在这里收到一个错误:
t.rb:6:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
Run Code Online (Sandbox Code Playgroud)
如果我指定绝对路径,它就会消失:
file = IniFile.load('/User/demo1/.config')
Run Code Online (Sandbox Code Playgroud)
但我不想对位置进行硬编码。如何解析~Ruby 中的路径?
对于这种情况,Ruby 有一个方法。它是File::expand_path。
将路径名转换为绝对路径名。除非给出了 dir_string,否则从进程的当前工作目录引用相对路径,在这种情况下,它将用作起点。给定的路径名可能以“~”开头,它扩展到进程所有者的主目录(必须正确设置环境变量 HOME)。
“~user”扩展到指定用户的home目录。
require 'inifile'
# read an existing file
file = IniFile.load(File.expand_path('~/.config'))
Run Code Online (Sandbox Code Playgroud)