[英]Using environment variables in a file path
I want to use an input path
in the following code: 我想在以下代码中使用输入path
:
File.exists?(File.expand_path(path))
Can I use environment variables in path
, and what should the syntax be? 我可以在path
使用环境变量,语法应该是什么?
You can use standard ruby string interpolation (though it's a little bit wordy) 你可以使用标准的红宝石字符串插值(虽然它有点罗嗦)
path = "log/#{ENV['RAILS_ENV']}.log" # or whatever
# >> "log/development.log"
To expand environment variables, you should do it yourself: 要扩展环境变量,您应该自己完成:
def expand_env(str)
str.gsub(/\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/) { ENV[$1] }
end
expand_env("${SHELL}:%USER%:$PAGER")
# => "/bin/bash:amadan:less"
(both Windows-style and Unix-style are supported, but only the basic substitution, and not any crazy stuff that bash is capable of). (支持Windows风格和Unix风格,但只支持基本替换,而不是bash能够做的任何疯狂的事情)。
为了便于携带,最好使用File::join
和ENV
Hash:
File.exists?( File.join(ENV['MY_VAR'],'bin') )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.