How to Upcase First Letter and Downcase the Rest in a Ruby String?

To make the first letter of a Ruby string uppercase/upcase and the remaining string lowercase/downcase, you can simply use the String#capitalize method, for example, like so:

str = "FOO BAR"
cap_str = str.capitalize

print cap_str #=> "Foo bar"

When using the String#capitalize method, you should consider the following:

  • It returns a new string with first letter capitalized and all remaining characters in lowercase (regardless of the case in the original string);
  • It does not follow any grammar-specific capitalization rules (such as capitalizing the first letter at the start of each new sentence or after certain punctuations, etc.).

Consider, for example, the following, where there are two sentences in the string, but only the first letter of the entire string is capitalized and all remaining words are converted to lowercase:

str = "fOO BAR BAZ. Qux Qaz Quux."
cap_str = str.capitalize

print cap_str #=> "Foo bar baz. qux qaz quux."

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.