Replace string by holding the box (uppercase/lowercase)

Asked

Viewed 254 times

3

How best to replace a pattern with a string keeping the box?

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

1 answer

3


You use the method gsub of the string to do the substitution using regular expression, but instead of passing a second fixed parameter, use a block of code to process each snippet found according to upper and lower case, which is already another challenge.

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

First, the function below converts the characters into 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 function split to break the two strings into character arrays. Then, the function zip creates a pair array. For example, strings bar and foo would generate the array `[b,f],[a,o],[r,o]].

Then, in the second line, the function map generates a new array based on the value returned by the code block. The block checks whether the current character p string padrao is uppercase and if it is it returns the corresponding character a string alvo uppercase, otherwise it force 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 by following the pattern:

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

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

See the functional example in Ideone

  • 1

    That’s the idea. Since I’m a beginner in language there are some things I still need to study to get a better understanding of your code. Thanks for the feedback and excellent explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.