Why does Rails titlecase add a space to a name?

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

    Edited (inspired by The Tin Man's suggestion)

    A hack will be:

    class String
      def titlecase
        gsub(/(?:_|\b)(.)/){$1.upcase}
      end
    end
    
    p "john mark McMillan".titlecase
    # => "John Mark McMillan"
    

    Note that the string 'john mark McMillan' is inconsistent in capitalization, and is somewhat unexpected as a human input, or if it is not from a human input, you probably should not have the strings stored in that way. A string like 'john mark mc_millan' is more consistent, and would more likely appear as a human input if you define such convention. My answer will handle these cases as well:

    p "john mark mc_millan".titlecase
    # => "John Mark McMillan"
    

提交回复
热议问题