Why does Rails titlecase add a space to a name?

前端 未结 10 1172
我在风中等你
我在风中等你 2021-02-05 10:28

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

John Mark McMillan

and it turns it into:

>> \"john mark McM         


        
10条回答
  •  温柔的废话
    2021-02-05 10:57

    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 
    

提交回复
热议问题