Converting upper-case string into title-case using Ruby

Viewed 47566

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 HERE" to "My String Here".

I know I can use the .downcase method, but that would make everything lower case ("my string here"). I'm scanning all lines in a file and doing this change, so is there a regular expression I can use through ruby to achieve this?

Thanks!

10 Answers

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

Related