这是您寻求的动态方法:
urls = [
'%MY_SERVER/json/data/mydata?someparameter',
'%MY_OTHER_SERVER/json/data/mydata?somethingdifferent=thisorthat'
]
name_regex = /(%\w+)/
ENV['%MY_SERVER'] = 'http://google.com'
replaced = urls.map do |s|
s.gsub name_regex do |env_name|
if ENV[env_name]
ENV[env_name] # replace
else
env_name # leave it untouched
end
# or, the same thing, but shorter
# ENV[env_name] || env_name
end
end
puts replaced
# >> http://google.com/json/data/mydata?someparameter
# >> %MY_OTHER_SERVER/json/data/mydata?somethingdifferent=thisorthat
你只需要扫描你的输入字符串并找到所有看起来像占位符的东西。幸运的是,您的字符串格式清晰。然后,您只需在ENV
. 如果占位符的值缺失,则不会被替换。