2014-09-10 57 views
0

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 

回答

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" 
+0

我建议排序后资本 – 2014-09-10 13:39:28

+0

谢谢@Santosh&alex提示之后的排序。这很好, **' to_display = the_data.map(&:upcase).sort.join(“\ n”)** – davidt 2014-09-10 13:50:49