Ok, say I have an array like so [[z,1], [d,3], [e,2]], how can I sort this array by the second element of each constituent array? So that my array would look like the following?
arr = [[:z,1], [:d,3], [:e,2]]
arr.sort {|a,b| a[1] <=> b[1]}
# => [[:z, 1], [:e, 2], [:d, 3]]
Or as user @Phrogz points out, if the inner arrays have exactly two elements each:
arr.sort_by{|x,y|y} # => [[:z, 1], [:e, 2], [:d, 3]]
arr.sort_by(&:last) # => [[:z, 1], [:e, 2], [:d, 3]]
As user maerics answer it provides Ascending sorting.This answer is very useful for me thanks. For Descending sorting i use -
arr = [[:z,1], [:d,3], [:e,2]]
arr.sort {|a,b| a[1] <=> b[1]}.reverse
#=> [[:d, 3], [:e, 2], [:z, 1]]