Capitalizing titles in Ruby - another take...
I basically extended his idea to be more flexible and added ! methods to modify the string in place. I chose to use a different regex selector because using "\b" breaks on apostrophes and leave you with words like "You'Re" instead of "You're"...
1 2 3 class String 4 5 def titlecase() 6 ignore_list = %w{of etc and by the for on is at to but nor or a via} 7 capitalize_all_ex(ignore_list) 8 end 9 10 def titlecase!() 11 ignore_list = %w{of etc and by the for on is at to but nor or a via} 12 capitalize_all_ex!(ignore_list) 13 end 14 15 def capitalize_all(force_downcase = true) 16 ignore_list = %w{} 17 capitalize_all_ex(ignore_list, force_downcase) 18 end 19 20 def capitalize_all!(force_downcase = true) 21 ignore_list = %w{} 22 capitalize_all_ex!(ignore_list, force_downcase) 23 end 24 25 def capitalize_all_ex(ignore_list, force_downcase = true) 26 # if force_downcase is true then the 27 # string is, um, downcased first :-) 28 if force_downcase 29 self.downcase.gsub(/[\w\']+/){ |w| 30 ignore_list.include?(w) ? w : w.capitalize 31 } 32 else 33 self.gsub(/[\w\']+/){ |w| 34 ignore_list.include?(w) ? w : w.capitalize 35 } 36 end 37 end 38 39 def capitalize_all_ex!(ignore_list, force_downcase = true) 40 if force_downcase 41 self.replace(self.downcase.gsub(/[\w\']+/){ |w| 42 ignore_list.include?(w) ? w : w.capitalize 43 }) 44 else 45 self.replace(self.gsub(/[\w\']+/){ |w| 46 ignore_list.include?(w) ? w : w.capitalize 47 }) 48 end 49 end 50 end