A better capitalize method

I’m just creating an app that has a registration form and I want to ensure that people’s names have capital letters in the right places.

String#capitalize just capitalizes the first letter of a string so it’s not exactly what I want.

"laura ann".capitalize
=> "Laura ann"
=> "O'shea"

At a glance I couldn’t see any other ruby method or ActiveSupport method that does what I want here so a solution can be reached using String#gsub.

"laura ann".gsub(/\b([\S])/){|m| m.upcase}
=> "Laura Ann"

"o'shea".gsub(/\b([\S])/){|m| m.upcase}
=> "O'Shea"

2 thoughts on “A better capitalize method

  1. Thanks for pointing that out Paul, I wasn’t aware of the titlecase/titleize method. My example here is pretty crude as it is not unicode aware. I’ll see what I can do about that.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>