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

标签 ruby macos

如果我这样做:

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

require 'inifile'

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

关于ruby - 如何在 Ruby 中使用 '~' 指定文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28083413/

相关文章:

javascript - 在 Rails 4.2 中解析 POSTed multipart/form-data

ruby - 使用 rspec 在 ruby​​ gem 测试中加载 fixture

ruby - Selenium-Webdriver:找到元素后获取属性

macos - 如何使用 Rust 编写原生 Mac OS X GUI?

swift - macOS:从 CharacterPalette 获取表情符号(修订版)

ruby - 确定 Nokogiri 元素的子索引

ruby - 使用正则表达式查找多个开始和结束标记之间的内容

ios - 采样率更改后声音失真

python - matplotlib 可拖动图例在 Mac OS 10.8 上不可用吗?

objective-c - XCode 构建结果 : why is it so amazingly complex even for a hello world console app?