如何在Ruby中使用'〜'指定文件路径? [英] How to specify a file path using '~' in Ruby?

查看:124
本文介绍了如何在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’s home directory.

require 'inifile'

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

这篇关于如何在Ruby中使用'〜'指定文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆