3

I have an "array of arrays" that has two values included at a time.

array = [[:tuesday, 0.25], [:monday, 1], [:thursday, 0.75]]

I'd like to use the number in the "child" array to sort the "parent" array in descending order. The result would look like:

array = [[:monday, 1], [:thursday, 0.75], [:tuesday, 0.25]]

I'm not too sure where to begin here.

4 Answers 4

8

You can pass a block to the sort method like this:

array.sort { |a, b| b[1] <=> a[1] }
Sign up to request clarification or add additional context in comments.

Comments

4

I would be inclined to write

array.sort_by(&:last).reverse

Comments

3
array = [['Tuesday',0.25],['Monday',1],['Thursday',0.75]]
p array.sort_by{|a| -a[1]}
# => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]]

Comments

1

You could use sort to return a new sorted array (saved as new_array).

new_array = array.sort{|x, y| y[1] <=> x[1]}
# => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]]

This keeps the original array unchanged.

array
# => [["Tuesday", 0.25], ["Monday", 1], ["Thursday", 0.75]]

Or you change the order of the original array by using sort!.

array.sort!{|x, y| y[1] <=> x[1]}
# => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]]

array
# => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]]

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.