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 = arr.map { | 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"]
arr.map! { | item | item[0].upcase + item[1..-1] }
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.