Question

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.

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!

Was it helpful?

Solution

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.each do |s|
    s.gsub!('This is some sample text', 'replacement')
end

OTHER TIPS

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"] 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top