Trying to refactor this into one line to get all vowels in a string to be capitalized. I tried using a hash, but that failed. Still too new at Ruby to know of any alternatives, despite my best efforts to look it up. something like.... 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
The best way is
str.tr('aeiou', 'AEIOU')
String#tr
Returns a copy of
str
with the characters infrom_str
replaced by the corresponding characters into_str
. If to_str is shorter than from_str, it is padded with its last character in order to maintain the correspondence.
You can use gsub
's second parameter, which is a replacement hash:
str.gsub!(/[aeiou]/, 'a' => 'A', 'e' => 'E', 'i' => 'I', 'o' => 'O', 'u' => 'U')
or, alternatively, pass a block:
str.gsub!(/[aeiou]/, &:upcase)
Both will return:
'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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With