Converting upper-case string into title-case using Ruby

后端 未结 10 1403
小鲜肉
小鲜肉 2020-12-25 10:46

I\'m trying to convert an all-uppercase string in Ruby into a lower case one, but with each word\'s first character being upper case. Example:

convert \"MY STRING HE

10条回答
  •  醉酒成梦
    2020-12-25 11:27

    The ruby core itself has no support to convert a string from upper (word) case to capitalized word case.

    So you need either to make your own implementation or use an existing gem.

    There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:

    require 'lucky_case'
    
    # to get capital word case as string
    LuckyCase.capital_word_case('MY STRING HERE')    # => 'My String Here'
    # or the opposite way
    LuckyCase.upper_word_case('Capital Word Case')   # => 'MY STRING HERE'
    

    You can even monkey patch the String class if you want to:

    require 'lucky_case/string'
    
    'MY STRING HERE'.capital_word_case  # => 'My String Here'
    'MY STRING HERE'.capital_word_case! # => 'My String Here' and overwriting original
    

    Have a look at the offical repository for more examples and documentation:

    https://github.com/magynhard/lucky_case

提交回复
热议问题