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.

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 - Ruby / Rails

Date:September 21, 2015