8

Ruby で gsub メソッドを使用して操作しようとしている文字列があります。問題は、元のテキストを検索して置き換えるために反復処理する必要がある文字列の動的配列があることです。

たとえば、次の元の文字列 (これは私が作業しているサンプル テキストであり、すべてが機能することを願っています) があり、検索して置換したい項目の配列があるとします。

事前に助けてくれてありがとう!

4

3 に答える 3

20

これはあなたが探しているものですか?

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"] 
于 2010-11-01T02:45:10.433 に答える
13
a = ['This is some sample text',
     'This is some sample text',
     'This is some sample text']

a は配列の例であり、配列をループして値を置き換えます

a.each do |s|
    s.gsub!('This is some sample text', 'replacement')
end
于 2010-11-01T02:47:01.083 に答える