Ruby/Rails working with gsub and arrays

dennismonsewicz picture dennismonsewicz · Nov 1, 2010 · Viewed 25.2k times · Source

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!

Answer

nonopolarity picture nonopolarity · Nov 1, 2010

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