如何在 Ruby 中使用 '~' 指定文件路径?

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

如果我这样做:

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 中的路径?

当在命令行的路径中给出 ~ 时,shell 将 ~ 转换为用户的主目录。 Ruby 不会那样做。

您可以使用以下内容替换 ~

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

或仅将文件引用为:

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

或:

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

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’s home directory.

require 'inifile'

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