In Ruby, you can make all strings in an array of strings uppercase by calling the String#upcase
method on every element of the array using Array#map
, for example, like so:
arr = ["foo", "Bar", "bAz"] new_arr = arr.map { |item| item.upcase } 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(&:upcase) print new_arr #=> ["FOO", "BAR", "BAZ"]
Using either of the above would create a new array with all strings in the array in uppercase. 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!(&:upcase) 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.