Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor multiple gsub statements into 1

Tags:

ruby

gsub

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
like image 370
Nate Beers Avatar asked Dec 26 '22 08:12

Nate Beers


2 Answers

The best way is

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

String#tr

Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character in order to maintain the correspondence.

like image 87
Arup Rakshit Avatar answered Jan 14 '23 20:01

Arup Rakshit


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"
like image 22
Uri Agassi Avatar answered Jan 14 '23 19:01

Uri Agassi