我想在字符串中查找给定子字符串的实例,并随机替换它:不是在它的每个实例中,而是仅仅是esporadically。 我正在考虑为子串的每个实例使用.each方法,然后使用rand在代码块内部根据结果替换它。 但是我对如何在这种情况下实现.each方法感到有些困惑。有人可以帮忙吗? (我使用的是Ruby 1.9)
答案 0 :(得分:4)
您可以使用String#gsub
的块变体:
s = 'foo bar foo bar foo bar foo bar'
# and you want to change random instances of "foo" with "baz":
s.gsub(/foo/){|m| rand(2) == 0 ? 'baz' : m}
#=> "baz bar foo bar baz bar foo bar"
答案 1 :(得分:0)
# this is original string
mystring = "some long string"
# this is given substring
substring = "some substring"
# this is raplace string (should be blank)
replace = "some substring replace"
# this is a loop
mystring.split(substring).inject{|new, chunk| new += (rand(2) == 0 ? substring : replace) + chunk }
例如:
mystring = "hello hello my dear friends! hello and goodbye after hello!"
substring = "hello"
replace = "pinky"
mystring.split(substring).inject{|new, chunk| new += (rand(2) == 0 ? substring : replace) + chunk }
#=> "hello pinky my dear friends! pinky and goodbye after hello!"