ruby 如何将数组的每个元素大写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11402362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:16:06  来源:igfitidea点击:

How can I uppercase each element of an array?

rubyarrays

提问by Michael Durrant

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

回答by Todd A. Jacobs

Return a New Array

返回一个新数组

If you want to return an uppercased array, use #map:

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

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

Update Array in Place

就地更新数组

If you want to uppercase the array in-place, use #map!instead:

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

array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
array.map!(&:upcase)
array
=> ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]

回答by Sergio Tulentsev

This should work:

这应该有效:

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

Or, if you want to save some CPU cycles

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

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

回答by christianblais

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.

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