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?
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(" ")
end
end
"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 > Benchmark.ms 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 > Benchmark.ms 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With