Alex Rivera | Logout

Why does Rails titlecase add a space to a name?

Asked 2011-04-11T00:10:55.253
19

Why does the titlecase 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
end

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?

Edit
Report

1 Answer

3

If all you want is to ensure that each word starts with a capital:

class String
  def titlecase2
    self.split(' ').map { |w| w[0] = w[0].upcase; w }.join(' ')
  end
end

irb(main):016:0> "john mark McMillan".titlecase2
=> "John Mark McMillan"
answered 2011-04-11T00:21:45.003

Your Answer