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

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 = arr.map { |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 = arr.map(&:capitalize)

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"]
arr.map!(&:capitalize)

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

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.