26

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? [[z,1], [e,2], [d,3]]?

2

2 Answers 2

48
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]]
Sign up to request clarification or add additional context in comments.

4 Comments

Or more simply: arr.sort_by{|s,n| n } or even arr.sort_by(&:last) (in Ruby 1.9).
@Phrogz Prefer sort because in ruby 2.4 (since 2.0 in fact or even before) sort_by doesn't exist but only sort_by! and the doc says that: The result is not guaranteed as stable. When two keys are equal, the order of the corresponding elements is unpredictable. So in order to use sort_by! you must have uniq keys. So @maerics please edit your post to say that or remove sort_by.
@noraj note that arrays are Enumerable#sort_by since at least v1.8.7 and stability was not requested in the question.
what about sorting by second column and then any ties would be sorted by the first column?
2

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

2 Comments

You can save the "reverse" call by simply doing arr.sort{|a,b|| b[1] <=> a[1]} (note the reverse order of the operands of the comparison operator).
you have a typo in your code, the correct code is arr.sort{|a,b| b[1] <=> a[1]}. you have inserted a pipe character too much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.