简单的数组排序和大写

时间:2014-09-10 12:58:12

标签: ruby

Ruby的新手并尝试一些东西。 下面的代码是在对数组进行排序时将数组转换为字符串并显示已排序的结果。我正在努力的是使用大写方法来限制所有排序的单词。

the_data = ["dog", "cat", "fish", "zebra", "swan", "rabbit", "horse", "albatros", "frog", "mouse", "duck"]

puts "\nThe array:\n"
puts the_data
puts "\n"

puts "\nThe sorted array, capitalized:\n"
to_display =  the_data.sort.join(("\n").capitalize)
puts to_display

1 个答案:

答案 0 :(得分:3)

您可以使用Array#map来大写Array

的每个字词
to_display =  the_data.sort.map(&:capitalize).join("\n")
# => "Albatros\nCat\nDog\nDuck\nFish\nFrog\nHorse\nMouse\nRabbit\nSwan\nZebra"

如果要将所有字母大写,可以使用upcase

to_display =  the_data.sort.map(&:upcase).join("\n")
# => "ALBATROS\nCAT\nDOG\nDUCK\nFISH\nFROG\nHORSE\nMOUSE\nRABBIT\nSWAN\nZEBRA"