为什么titlecase弄乱了名字?我有:
John Mark McMillan
它变成:
>> "john mark McMillan".titlecase => "John Mark Mc Millan"
为什么还有空格添加到姓氏?
基本上我有这个在我的模型:
before_save :capitalize_name def capitalize_name self.artist = self.artist.titlecase end
解决方法
如果Rails不够好,你可以随时自己做:
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"
我的解决方案
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
正则表达式解决方案
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