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.