【发布时间】:2017-01-24 00:09:06
【问题描述】:
我想获取字符串 foofoofoo,将 foo 映射到 bar,并将所有单独的替换作为数组返回 - ['barfoofoo', 'foobarfoo', 'foofoobar']
这是我最好的:
require 'pp'
def replace(string, pattern, replacement)
results = []
string.length.times do |idx|
match_index = (Regexp.new(pattern) =~ string[idx..-1])
next unless match_index
match_index = idx + match_index
prefix = ''
if match_index > 0
prefix = string[0..match_index - 1]
end
suffix = ''
if match_index < string.length - pattern.length - 1
suffix = string[match_index + pattern.length..-1]
end
results << prefix + replacement + suffix
end
results.uniq
end
pp replace("foofoofoo", 'foo', 'bar')
这可行(至少对于这个测试用例),但看起来太冗长和hacky。我可以做得更好吗,也许通过使用带有块或类似的string#gsub?
【问题讨论】:
-
我不认为 Ruby 提供了开箱即用的功能。
-
@JaredBeck 只是为了澄清一下,输入字符串作为示例给出 - 真正的问题是支持任意字符串,并使用提供的替换替换任何索引处的模式匹配。因此,例如,
replace('foofof', 'f|o|fo', 'x')应该产生['xoofof', 'xofof', 'fxofof', 'fxxfof', 'foxfof', <etc.>] -
请根据您最后的评论更新您的问题。此外,
'f|o|fo'是一个字符串,而不是一个模式。如果你想要一个模式,你应该使用/f|o|fo/。