本文介绍了为什么 Rails 的 titlecase 会为名称添加一个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 titlecase 把名字弄乱了?我有:

Why does the titlecase mess up the name? I have:

John Mark McMillan

然后变成:

>> "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

我试图确保数据库中的所有名称都是 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?

推荐答案

如果 Rails 不够好,你总是可以自己做:

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:

我的解决方案:

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 

这篇关于为什么 Rails 的 titlecase 会为名称添加一个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 06:21