Execute method on match result with #Ruby regular expression replacement (Example: Uppercase letters)

--Capture using parentheses --You can execute any method on the match result with gsub + block notation

"ab cd ef".gsub(/(ab|ef)/) { "#{$1.upcase}" }
# => "AB cd EF"

Bad Case

If it is not a block, if there are multiple match results, the replacement results will all be the same.

"ab cd ef".gsub(/(ab|ef)/, "#{$1.upcase}")
# "EF cd EF"

reference

How to change case of letters in string using RegEx in Ruby - Stack Overflow

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3169

Recommended Posts

Execute method on match result with #Ruby regular expression replacement (Example: Uppercase letters)
ruby Uppercase letters
Ruby regular expression
Ruby on Rails Refactoring method example summary around MVC
Extract a string starting with a capital letter with a regular expression (Ruby)