Interpolating environment variables into a string in Ruby using String#scan
ruby, string
Solution
irb(main):018:0> "how %%EDITOR%% now %%HOME%% brown cow".gsub(/%%.*?%%/) do |e|
irb(main):019:1* ENV[e.gsub '%', '']
irb(main):020:1> end
=> "how vi now /Users/ross brown cow"
Slightly different, and incorporating your default action...
irb(main):045:0> "how %%EDITOR%% now %%HOME%% brown %%X%% cow".gsub(/%%(.*?)%%/) do |e|
irb(main):046:1* t = ENV[$1]
irb(main):047:1> t.nil? ? "my action" : t
irb(main):048:1> end
=> "how vi now /Users/ross brown my action cow"
irb(main):049:0>
Problem
I'm trying to interpolate environment variables into a string in Ruby and not having much luck. One of my requirements is to do something (log an error, prompt for input, whatever) if a placeholder is found in the initial string that has no matching environment variable. It looks like the block form of String#scan is what I need. Below is an irb session of my failed attempt. ``` irb(main):014:0> raw_string = "need to replace %%FOO%% and %%BAR%% in here" => "need to replace %%FOO%% and %%BAR%% in here" irb(main):015:0> cooked_string << raw_string => "need to replace %%FOO%% and %%BAR%% in here" irb(main):016:0> raw_string.scan(/%%(.*?)%%/) do |var| irb(main):017:1* cooked_string.sub!("%%#{var}%%", ENV[var]) irb(main):018:1> done irb(main):019:1> end TypeError: cannot convert Array into String from (irb):17:in `[]' from (irb):17 from (irb):16:in `scan' from (irb):16 from :0 ``` If I use `ENV["FOO"]` to manually interpolate one of those, it works fine. I'm banging my head against the desk. What am I doing wrong? Ruby is 1.8.1 on RHEL or 1.8.7 on Cygwin.