Get the top 5 elements : sort « Array « Ruby






Get the top 5 elements


l = [1, 60, 21, 100, -5, 20, 60, 22, 85, 91, 4, 66]
sorted = l.sort

# The top 5
p sorted[-5...sorted.size]
# => [60, 66, 85, 91, 100]

 








Related examples in the same category

1.apply the sort (or sort!, for in-place changes)
2.Get the bottom 5 elements
3.ArgumentError: comparison of Fixnum with String failed
4.Sort object array by object attribute