Ruby capitalize every word first letter

前端 未结 8 804
名媛妹妹
名媛妹妹 2020-12-12 10:47

I need to make the first character of every word uppercase, and make the rest lowercase...

manufacturer.MFA_BRAND.first.upcase

is only sett

相关标签:
8条回答
  • 2020-12-12 11:32

    In Rails:

    "kirk douglas".titleize => "Kirk Douglas"
    #this also works for 'kirk_douglas'
    

    w/o Rails:

    "kirk douglas".split(/ |\_/).map(&:capitalize).join(" ")
    
    #OBJECT IT OUT
    def titleize(str)
      str.split(/ |\_/).map(&:capitalize).join(" ")
    end
    
    #OR MONKEY PATCH IT
    class String  
      def titleize
        self.split(/ |\_/).map(&:capitalize).join(" ")
      end
    end
    

    w/o Rails (load rails's ActiveSupport to patch #titleize method to String)

    require 'active_support/core_ext'
    "kirk douglas".titleize #=> "Kirk Douglas"
    

    (some) string use cases handled by #titleize

    • "kirk douglas"
    • "kirk_douglas"
    • "kirk-douglas"
    • "kirkDouglas"
    • "KirkDouglas"

    #titleize gotchas

    Rails's titleize will convert things like dashes and underscores into spaces and can produce other unexpected results, especially with case-sensitive situations as pointed out by @JamesMcMahon:

    "hEy lOok".titleize #=> "H Ey Lo Ok"
    

    because it is meant to handle camel-cased code like:

    "kirkDouglas".titleize #=> "Kirk Douglas"
    

    To deal with this edge case you could clean your string with #downcase first before running #titleize. Of course if you do that you will wipe out any camelCased word separations:

    "kirkDouglas".downcase.titleize #=> "Kirkdouglas"
    
    0 讨论(0)
  • 2020-12-12 11:35

    try this:

    puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')
    
    #=> One Two Three Four
    

    or

    puts 'one TWO three foUR'.split.map(&:capitalize)*' '
    
    0 讨论(0)
提交回复
热议问题