使用 gsub 和数组的 Ruby/Rails
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4066349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby/Rails working with gsub and arrays
提问by dennismonsewicz
I have a string that I am trying to work with in using the gsub method in Ruby. The problem is that I have a dynamic array of strings that I need to iterate through to search the original text for and replace with.
我有一个字符串,我试图在 Ruby 中使用 gsub 方法来处理它。问题是我有一个动态的字符串数组,我需要遍历它来搜索原始文本并将其替换。
For example if I have the following original string (This is some sample text that I am working with and will hopefully get it all working) and have an array of items I want to search through and replace.
例如,如果我有以下原始字符串(这是我正在使用的一些示例文本,希望能使其全部正常工作)并且有一组我想要搜索和替换的项目。
Thanks for the help in advance!
我在这里先向您的帮助表示感谢!
回答by nonopolarity
Is this what you are looking for?
这是你想要的?
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"]
回答by thenengah
a = ['This is some sample text',
'This is some sample text',
'This is some sample text']
so a is the example array, and then loop through the array and replace the value
所以 a 是示例数组,然后遍历数组并替换值
a.each do |s|
s.gsub!('This is some sample text', 'replacement')
end

