0

I am looking for a proper way to sort by ascending or descending a complex array.

arr = [[100, 200, 300], [100, 250, 600], [50, 10, 1030]]

I would like to sort this array based on the target value [value, value, target_value]

I have my own way to do this but it seems ugly and slow.

Do we have a proper way to do this in ruby?

Thanks in advance.

1
  • 1
    What's the expected output? Commented Feb 26, 2015 at 21:28

3 Answers 3

4

Or even shorter like this:

arr.sort_by(&:last)

If you need it in descend order:

arr.sort_by(&:last).reverse

To do the sorting and reversing in two steps seems laborious, but it is actually faster than the sort {} syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer works as well but how do i define ascend or descend?
3
[[100, 200, 300], [100, 250, 600], [50, 10, 1030]].sort_by{|x| x[2]}

1 Comment

you can append .reverse
1

Here's a way to do it more explicitly:

arr.sort { |a, b| a[2] <=> b[2] }

For a descending sort, just reverse the order:

arr.sort { |a, b| b[2] <=> a[2] }

Comments

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.