2011-07-16 137 views
2

我想查找字符串內給定子字符串的實例,並隨機替換它:不是在它的每個實例中,而是僅在本地。 我正在考慮對子字符串的每個實例使用.each方法,然後在代碼塊內使用rand取代或取消取決於結果。 但是我有點在如何在這種情況下實現.each方法。誰能幫忙? (我使用Ruby 1.9)將字符串中的子串的隨機實例替換爲字符串(ruby)

回答

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

不知道我可以迭代gsub。涼! – fl00r

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!" 
+0

我真的不明白那是什麼做的。什麼注射做,確切地說?它傳遞給代碼塊的參數是什麼? –

+0

我編輯了我的答案 – fl00r