How can I turn an array of elements into uppercase? Expected output would be:
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] => ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
The following didn't work and left them as lower case.
Day.weekday.map(&:name).each {|the_day| the_day.upcase } => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
split() method. Convert all the elements in each and every word in to lowercase using string. toLowerCase() method. Loop through first elements of all the words using for loop and convert them in to uppercase.
To convert all array elements to lowercase:Use the map() method to iterate over the array. On each iteration, call the toLowerCase() method to convert the string to lowercase and return the result. The map method will return a new array containing only lowercase strings.
String string = "Contains some Upper and some Lower."; String string2 = string. toUpperCase(); String string3 = string. toLowerCase(); These two methods transform a string into all uppercase or all lowercase letters.
If you want to return an uppercased array, use #map:
array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] # Return the uppercased version. array.map(&:upcase) => ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"] # Return the original, unmodified array. array => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
As you can see, the original array is not modified, but you can use the uppercased return value from #map anywhere you can use an expression.
If you want to uppercase the array in-place, use #map! instead:
array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] array.map!(&:upcase) array => ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With