Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails working with gsub and arrays

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!

like image 576
dennismonsewicz Avatar asked Nov 01 '10 02:11

dennismonsewicz


People also ask

How do you use GSUB in rails?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

Does GSUB use regex?

Regular expressions (shortened to regex) are used to operate on patterns found in strings. They can find, replace, or remove certain parts of strings depending on what you tell them to do.

What is the difference between gsub () and sub ()?

The sub() and gsub() function in R is used for substitution as well as replacement operations. The sub() function will replace the first occurrence leaving the other as it is. On the other hand, the gsub() function will replace all the strings or values with the input strings.

What is GSUB?

In Ruby, Gsub is a method that can be called on strings. It replaces all instances of a substring with another one inside the string. Sub is short for "substitute," and G stands for "global." Think of Gsub like a "replace all" function. The general pattern is str. gsub("target string", "replacement string").


2 Answers

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"] 
like image 118
nonopolarity Avatar answered Sep 27 '22 18:09

nonopolarity


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
like image 45
thenengah Avatar answered Sep 27 '22 20:09

thenengah