Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I uppercase each element of an array?

Tags:

arrays

ruby

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"]  
like image 779
Michael Durrant Avatar asked Jul 09 '12 20:07

Michael Durrant


People also ask

How do you convert all strings to title caps in a string array?

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.

How do I convert all elements to lowercase in array?

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.

How do you make a string all capitals?

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.


1 Answers

Return a New Array

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.

Update Array in Place

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"] 
like image 199
Todd A. Jacobs Avatar answered Nov 09 '22 00:11

Todd A. Jacobs