Capitalize Only First Letter Of Each Word In A String And Leave The Rest Of The Letters Alone

Posted By Weston Ganger

You would think titleize or capitalize string methods would be able to handle the fact that I only want the first letter touched. Instead they will lowercase the rest of the letters in the words.


puts "AngularJS".titleize #=> "Angular Js"
puts "AngularJS".capitalize #=> "Angularjs"

So those wont work, heres a trick that will. Im not sure it the most efficient way totally possible but I didnt find any articles about how to do this. So heres my version


str = "angularJS"
puts str[0].upcase + str[1..-1] #=> "AngularJS"

str = "i really LOVE angularJS"
puts str.split.map{|x| x[0].upcase + x[1..-1]}.join(" ") #=> "I Really LOVE AngularJS"

# OR a Better answer posted by Pavel Pravosud
puts str.gsub(/\b\w/, &:upcase) #=> "I Really LOVE AngularJS"

Article Topic:Software Development - Rails

Date:September 21, 2015