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!
Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase : "hello James!". downcase #=> "hello james!"
Converting a string to uppercase can be achieved using the upcase method. It converts the characters in a string to its corresponding uppercase. It returns the uppercase of characters in a string.
Ruby strings have methods to convert them to uppercase and lowercase. The method names of the methods are upcase and downcase respectively. Calling the downcase or upcase method on a string will return the lowercase or uppercase version of the string, but the original variable won't change.
To make titlecased version of a string, you use the string title() method. The title() returns a copy of a string in the titlecase. The title() method converts the first character of each words to uppercase and the remaining characters in lowercase.
If you're using Rails (really all you need is ActiveSupport, which is part of Rails), you can use titleize
:
"MY STRING HERE".titleize # => "My String Here"
If you're using plain Ruby but don't mind loading a small amount of ActiveSupport you can require it first:
require 'active_support/core_ext/string/inflections' # => true "MY STRING HERE".titleize # => "My String Here"
N.B. By default titleize
doesn't handle acronyms well and will split camelCaseStrings into separate words. This may or may not be desirable:
"Always use SSL on your iPhone".titleize # => "Always Use Ssl On Your I Phone"
You can (partially) address this by adding "acronyms":
require 'active_support/core_ext/string/inflections' # If not using Rails ActiveSupport::Inflector.inflections do |inflect| inflect.acronym 'SSL' inflect.acronym 'iPhone' end "Always use SSL on your iPhone".titleize # => "Always Use SSL On Your IPhone"
For those who speak the Queen's English (or who struggle to spell titleize), there's no .titleise
alias but you can use .titlecase
instead.
"HELLO WORLD HOW ARE YOU".gsub(/\w+/) do |word| word.capitalize end #=> "Hello World How Are You"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With