How to Upcase First Letter and Downcase the Rest in a Ruby Array of Strings?

Uppercase first letter in Ruby array of strings and lowercase the remainder

In Ruby, you can capitalize every string in an array of strings by calling the String#capitalize method on each element using Array#map, for example, like so:

arr = ["foo Bar", "baz", "qux"]
new_arr = { |item| item.capitalize }

print new_arr #=> ["Foo bar", "Baz", "Qux"]

This would make the first letter of every string uppercase and make everything else lowercase (as opposed to making only the first letter uppercase whilst leaving the remaining string unchanged).

You could also shorten this by using the &: syntax, for example, like so:

arr = ["foo Bar", "baz", "qux"]
new_arr =

print new_arr #=> ["Foo bar", "Baz", "Qux"]

Using either of the above would create a new array with all strings in the array having the first letter in uppercase and the remaining string in lowercase. If you want to mutate the original array instead, then you simply need to use Array#map! instead of Array#map. For example:

arr = ["foo Bar", "baz", "qux"]!(&:capitalize)

print arr #=> ["Foo bar", "Baz", "Qux"]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.