How to Convert an Array of Strings to Lowercase in Ruby?

In Ruby, you can make all strings in an array of strings lowercase by calling the String#downcase method on every element of the array using Array#map, for example, like so:

arr = ["FOO", "Bar", "bAz"]
new_arr = arr.map { |item| item.downcase }

print new_arr #=> ["foo", "bar", "baz"]

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

arr = ["FOO", "Bar", "bAz"]
new_arr = arr.map(&:downcase)

print new_arr #=> ["foo", "bar", "baz"]

Using either of the above would create a new array with all strings in the array 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, like so:

arr = ["FOO", "Bar", "bAz"]
arr.map!(&:downcase)

print arr #=> ["foo", "bar", "baz"]

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.