Why does Rails titlecase add a space to a name?

前端 未结 10 1171
我在风中等你
我在风中等你 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:36

    You may also encounter names with two capital letters, such as McLaren, McDonald etc.

    Have not spent time trying to improve it, but you could always do

    Code

    # Rails.root/config/initializers/string.rb
    class String
      def titleize_name
        self.split(" ")
          .collect{|word| word[0] = word[0].upcase; word}
          .join(" ").gsub(/\b('?[a-z])/) { $1.capitalize }
      end
    end
    

    Examples

    [2] pry(main)> "test name".titleize_name
    => "Test Name"
    [3] pry(main)> "test name-name".titleize_name
    => "Test Name-Name"
    [4] pry(main)> "test McName-name".titleize_name
    => "Test McName-Name"
    

提交回复
热议问题