Ruby/Rails使用gsub和数组

den*_*icz 7 ruby ruby-on-rails gsub

我有一个字符串,我正在尝试使用Ruby中的gsub方法.问题是我有一个动态的字符串数组,我需要迭代搜索原始文本并替换.

例如,如果我有以下原始字符串(这是我正在使用的一些示例文本,并希望将其全部工作)并且有一系列我想要搜索和替换的项目.

我在这里先向您的帮助表示感谢!

nop*_*ole 17

这是你想要的?

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"] 
Run Code Online (Sandbox Code Playgroud)


the*_*gah 13

a = ['This is some sample text',
     'This is some sample text',
     'This is some sample text']
Run Code Online (Sandbox Code Playgroud)

所以a是示例数组,然后遍历数组并替换值

a.each do |s|
    s.gsub!('This is some sample text', 'replacement')
end
Run Code Online (Sandbox Code Playgroud)