29

如何将元素数组转换为大写?预期输出为:

["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]  
=> ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]

以下内容不起作用,并将它们保留为小写。

Day.weekday.map(&:name).each {|the_day| the_day.upcase }
 => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] 
4

3 回答 3

64

返回一个新数组

如果要返回大写数组,请使用#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"]

如您所见,原始数组没有被修改,但您可以在任何可以使用表达式的地方使用#map 的大写返回值。

就地更新数组

如果要就地大写数组,请使用#map!反而:

array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
array.map!(&:upcase)
array
=> ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
于 2012-07-09T20:28:19.180 回答
7

这应该有效:

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

或者,如果您想节省一些 CPU 周期

Day.weekday.map{|wd| wd.name.upcase}
于 2012-07-09T20:14:53.563 回答
4

在您的示例中,将“每个”替换为“地图”。

虽然 'each' 遍历您的数组,但它不会创建包含块返回值的新数组。

于 2012-07-09T20:17:52.677 回答