Replace string by keeping the box (uppercase / lowercase)

3

What is the best way to replace a pattern with a string while holding the box?

For example, DAdo - > LAdo or dado - > lado .

    
asked by anonymous 05.02.2016 / 00:18

1 answer

3

You use the gsub method of the string to make the substitution using regular expression, but rather than passing a second fixed parameter, use a block of code to process each section found in all uppercase and lowercase letters, which it's another challenge.

I made a simple implementation of this process in two steps.

First, the function below converts the characters to a string alvo according to the string padrao :

def samecase(padrao, alvo)
    alvo.split("").zip(padrao.split(""))
        .map { |a, p| p.upcase == p ? a.upcase : a.downcase }
        .join("")
end

The first line of the function uses the split function to break the two strings into arrays of characters. Then, the zip function creates an array of pairs. For example, the strings bar and foo would generate the array '[[b, f], [a, o], [r, o]].

Then, in the second line, the map function generates a new array based on the value returned by the code block. The block checks if the current character p of the string padrao is uppercase and if it returns the corresponding character a of the string alvo in uppercase, otherwise it forces lowercase.

The last line simply joins the resulting characters into a new string.

Now, using the function described above, we can make a new function to perform the substitution following the pattern:

def replace_with_case(str, padrao, novo_valor) 
    str.gsub(/#{padrao}/i) { |matched| samecase(matched, novo_valor) }
end

The above routine gets a string str that will be searched for by the value of the parameter padrao and then replaced by the novo_valor transformed with the same "boxes" of the found text.

See the functional example in Ideone

    
05.02.2016 / 03:05