Interpolating environment variables into a string in Ruby using String # scan

I am trying to interpolate environment variables into a string in Ruby and not have much luck. One of my requirements is to do something (register an error, an invitation to enter, whatever) if the placeholder is found in the source line, which does not have a corresponding environment variable. It looks like the block form of String # scan is what I need. The following shows the 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"]one of them for manual interpolation, it works fine. I hit my head on the table. What am I doing wrong?

Ruby - 1.8.1 on RHEL or 1.8.7 on Cygwin.

+3
source share
1 answer
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"

...

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> 
+4

Source: https://habr.com/ru/post/1737278/


All Articles