Refactoring multiple gsub statements in 1

Trying to refactor this into one line to get all the vowels in the line, which will be uppercase. I tried using a hash, but that failed. There is still too much new in Ruby to know any alternatives, despite all my efforts to find it. sort of....str.gsub!(/aeiou/

def LetterChanges(str)
  str.gsub!(/a/, "A") if str.include? "a"
  str.gsub!(/e/, "E") if str.include? "e"
  str.gsub!(/i/, "I") if str.include? "i"
  str.gsub!(/o/, "O") if str.include? "o"
  str.gsub!(/u/, "U") if str.include? "u"
  puts str
end
+4
source share
2 answers

The best way -

str.tr('aeiou', 'AEIOU')

String#tr

Returns a copy strwith the characters in from_strreplaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character to maintain consistency.

+7
source

gsub , :

str.gsub!(/[aeiou]/, 'a' => 'A', 'e' => 'E', 'i' => 'I', 'o' => 'O', 'u' => 'U')

, , :

str.gsub!(/[aeiou]/, &:upcase)

:

'this is a test'.gsub!(/[aeiou]/, 'a' => 'A', 'e' => 'E', 'i' => 'I', 'o' => 'O', 'u' => 'U')
# => "thIs Is A tEst"

'this is a test'.gsub!(/[aeiou]/, &:upcase)
# => "thIs Is A tEst"
+3

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


All Articles