2010-11-01 59 views
5

我有一個字符串,我正嘗試在Ruby中使用gsub方法。問題是我有一個動態數組的字符串,我需要迭代搜索原始文本並替換。使用gsub和數組的Ruby/Rails

例如,如果我有以下原始字符串(這是我正在使用的一些示例文本,並且希望它能夠正常工作)並且有一組我想要搜索和替換的項目。

感謝您的幫助!

回答

10
a = ['This is some sample text', 
    'This is some sample text', 
    'This is some sample text'] 

所以是示例數組,然後循環通過陣列和替換值

a.each do |s| 
    s.gsub!('This is some sample text', 'replacement') 
end 
15

這是你在找什麼?

ruby-1.9.2-p0 > arr = ["This is some sample text", "text file"] 
=> ["This is some sample text", "text file"] 

ruby-1.9.2-p0 > arr = arr.map {|s| s.gsub(/text/, 'document')} 
=> ["This is some sample document", "document file"]