Ruby / Rails working with gsub and arrays

I have a line I'm trying to work with using the gsub method in Ruby. The problem is that I have a dynamic array of strings that I need to iterate over to search for the source text and replace it.

For example, if I have the following original line (this is some example of the text I'm working with, and hopefully this will work) and have an array of elements that I want to find and replace.

Thanks for the help in advance!

+5
source share
2 answers
a = ['This is some sample text',
     'This is some sample text',
     'This is some sample text']

so a is an example of an array, and then loop through the array and replace the value

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

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"] 
+15

All Articles