How to Capitalize First Letter in an Array of Strings in Ruby?

Learn how to capitalize every element of a Ruby array of strings

In Ruby, you can make the first letter of every string in an array of strings uppercase whilst leaving the remaining string unchanged using Array#map, for example, like so:

arr = ["foo Bar", "baz", "qux"]
new_arr = { | item | item[0].upcase + item[1..-1] }

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

This is different from using String#capitalize method, which capitalizes the first character of a string and makes the remaining string lowercase.

The code above would return a new array. However, if you want to mutate the original array, then you simply need to use Array#map! instead of Array#map. For example:

arr = ["foo Bar", "baz", "qux"]! { | item | item[0].upcase + item[1..-1] }

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.