替代的返回數組我想借此串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')
這起作用(至少對於這個測試用例來說),但是看起來太冗長而且很拗口。我可以做的更好,也許通過使用string#gsub
與塊或其他?
我不不認爲Ruby提供這樣的功能離子性。 –
@JaredBeck爲了澄清,輸入字符串作爲示例給出 - 真正的問題是支持任意字符串,並用所提供的替換替換任何索引處的模式匹配。例如,'replace('foofof','f | o | fo','x')'應該產生'['xoofof','xofof','fxofof','fxxfof','foxfof', ]' –
Anand
請根據您的最新評論更新您的問題。另外,''f | o | fo''是一個字符串,而不是一個模式。如果你想要一個模式,你應該使用'/ f | o | fo /'。 –