Trace Trace - 1 month ago 5x
Ruby Question

Why does Rails titlecase add a space to a name?

Why does the

mess up the name? I have:

John Mark McMillan

and it turns it into:

>> "john mark McMillan".titlecase
=> "John Mark Mc Millan"

Why is there a space added to the last name?

Basically I have this in my model:

before_save :capitalize_name

def capitalize_name
self.artist = self.artist.titlecase

I am trying to make sure that all the names are titlecase in the DB, but in situtations with a camelcase name it fails. Any ideas how to fix this?


You can always do it yourself if Rails isn't good enough:

class String
    def another_titlecase
        self.split(" ").collect{|word| word[0] = word[0].upcase; word}.join(" ")

"john mark McMillan".another_titlecase
 => "John Mark McMillan" 

This method is a small fraction of a second faster than the regex solution:

My solution:

ruby-1.9.2-p136 :034 > do
ruby-1.9.2-p136 :035 >     "john mark McMillan".split(" ").collect{|word|word[0] = word[0].upcase; word}.join(" ")
ruby-1.9.2-p136 :036?>   end
 =>  0.019311904907226562 

Regex solution:

ruby-1.9.2-p136 :042 > do
ruby-1.9.2-p136 :043 >     "john mark McMillan".gsub(/\b\w/) { |w| w.upcase }
ruby-1.9.2-p136 :044?>   end
 => 0.04482269287109375