简体   繁体   中英

Using environment variables in a file path

I want to use an input path in the following code:

File.exists?(File.expand_path(path))

Can I use environment variables in path , and what should the syntax be?

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).

为了便于携带,最好使用File::joinENV Hash:

File.exists?( File.join(ENV['MY_VAR'],'bin') )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM