Remove substrings in ruby

Given an array of strings,

array1 = ["abcdwillbegoneabcccc","cdefwilbegokkkabcdc"] 

and another array of strings that consist of patterns, for example. ["abcd","beg[o|p]n","bcc","cdef","h*gxwy"]

the task is to remove the substrings that match any line of the pattern. for example, the sample for this case should be:

 ["willbegonea","wilbegokkk"] 

because we removed substrings (prematch or postmatch as appropriate depending on the appearance position) that matched one of the patterns. Suppose that one or two matches will always occur at the beginning or at the end of each row in array 1.

Any ideas for an elegant solution above in ruby?

+4
source share
3 answers

How to create a single regex?

 array1 = ["abcdwillbegoneabcccc","cdefwilbegokkkabcdc"] to_remove = ["abcd","beg[o|p]n","bcc","cdef","h*gxwy"] reg = Regexp.new(to_remove.map{ |s| "(#{s})" }.join('|')) #=> /(abcd)|(beg[o|p]n)|(bcc)|(cdef)|(h*gxwy)/ array1.map{ |s| s.gsub(reg, '') } #=> ["willeacc", "wilbegokkkc"] 

Please note that my result is different from yours.

 ["willbegonea","wilbegokkk"] 

but I believe that this is correct, it removes "abcd", "begon" and "bcc" from the original, which seems to be needed.

+7
source

I see some potential errors here, in the event that you change the order of the lines of the template, you can get a different result; and also the second pattern can leave the string in a state that would correspond to the first, only now it's too late.

Assuming this data, I would go with Joanne. The only way I can improve a bit is to make regexen patterns, not strings, for example:

 [/abcd/,/beg[o|p]n/,/bcc/,/cdef/,/h*gxwy/].each do |pattern| string_to_test.gsub!(pattern,'') end 

But, of course, if the patterns come from somewhere else, maybe they should be strings.

+2
source

I think something like this should work:

 def gimme_the_substring(string_to_test) ["abcd","beg[o|p]n","bcc","cdef","h*gxwy"].each do |pattern| string_to_test.gsub!(/#{pattern}/,'') end return string_to_test end array1.map!{|s| gimme_the_substring(s)} 
+1
source

Source: https://habr.com/ru/post/1300385/


All Articles