Ruby capitalize every word first letter

前端 未结 8 803
名媛妹妹
名媛妹妹 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:16

    I used this for a similar problem:

    'catherine mc-nulty joséphina'.capitalize.gsub(/(\s+\w)/) { |stuff| stuff.upcase }
    

    This handles the following weird cases I saw trying the previous answers:

    • non-word characters like -
    • accented characters common in names like é
    • capital characters in the middle of the string
    0 讨论(0)
  • 2020-12-12 11:26
    "hello world".split.each{|i| i.capitalize!}.join(' ')
    
    0 讨论(0)
  • 2020-12-12 11:28

    If you are trying to capitalize the first letter of each word in an array you can simply put this:

    array_name.map(&:capitalize)

    0 讨论(0)
  • 2020-12-12 11:29

    Look into the String#capitalize method.

    http://www.ruby-doc.org/core-1.9.3/String.html#method-i-capitalize

    0 讨论(0)
  • 2020-12-12 11:30

    Another option is to use a regex and gsub, which takes a block:

    'one TWO three foUR'.gsub(/\w+/, &:capitalize)
    
    0 讨论(0)
  • 2020-12-12 11:31

    "hello world".titleize which should output "Hello World".

    0 讨论(0)
提交回复
热议问题