How can I uppercase each element of an array?

2020-02-26 04:01发布

问题:

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"] 

回答1:

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"]


回答2:

This should work:

Day.weekday.map(&:name).map(&:upcase)

Or, if you want to save some CPU cycles

Day.weekday.map{|wd| wd.name.upcase}


回答3:

In your example, replace 'each' with 'map'.

While 'each' iterates through your array, it doesn't create a new array containing the values returned by the block.



标签: ruby arrays