如何在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)
如果我指定绝对路径,它将消失:
It goes away if I specify an absolute path:
file = IniFile.load('/User/demo1/.config')
但是我不想对位置进行硬编码.如何将~
解析为Ruby中的路径?
But I do not want to hardcode the location. How can I resolve ~
to a path in Ruby?
推荐答案
Ruby针对这种情况提供了一种方法.它是 File::expand_path
.
Ruby has a method for this case. It is File::expand_path
.
将路径名转换为绝对路径名.除非给出dir_string,否则相对路径是从进程的当前工作目录中引用的,在这种情况下,它将用作起点.给定的路径名可以以〜"开头,该名称会扩展到流程所有者的主目录(必须正确设置环境变量HOME).
~user
会扩展到指定用户的home
目录.
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中使用'〜'指定文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!