jonjon
jonjon

Reputation: 3

How to sort a complex array in ruby

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.

Upvotes: 0

Views: 180

Answers (3)

spickermann
spickermann

Reputation: 107077

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.

Upvotes: 4

dwenzel
dwenzel

Reputation: 1434

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

Upvotes: 1

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42899

[[100, 200, 300], [100, 250, 600], [50, 10, 1030]].sort_by{|x| x[2]}

Upvotes: 3

Related Questions