0

I have a 2d array which is supposed to be a user ranking, based on points. I first init it:

ranked_user = []

Then I do some points calculations and push some stuff into the array:

ranked_user.push([user.id, user.username, user.location, points])

which results in

=> [[8, "Jhonny", "Berlin", 11], [9, "Ben", "Hamburg", 3], [10, "Hugo", "Munich", 6]]

now I want to sort that array based on the 4th value (points) in order to show the ranking. I've tried two things:

ranked_user.sort_by{|k|k[3]}

and

ranked_user.sort { |a, b| b[3] <=> a[3] }

I expect this:

=> [[9, "Ben", "Hamburg", 3], [10, "Hugo", "Munich", 6], [8, "Jhonny", "Berlin", 11]]

but the array simply is not sorted.

What do I do wrong?

3
  • Somehow, if I put that into an each loop it does work. If I plot it out in plain, it remains unsorted. Commented Jul 29, 2014 at 22:54
  • 1
    What do you mean? You must also remember that this doesn't change the array, if that is what you want you can use sort_by! Commented Jul 29, 2014 at 23:00
  • Iceman is right, just use sort_by! or just save the sorted array to a new local variable. Commented Jul 29, 2014 at 23:03

2 Answers 2

2

Just to add on to Morgan Laco's answer :

If you do :

ranked_user.sort_by{|k|k[3]}

Then ranked_user would still be unordered. Only the return is ordered.

So in order to change ranked_user, you would have to do either of these :

ranked_user = ranked_user.sort_by{|k|k[3]}
ranked_user.sort_by!{|k|k[3]}
Sign up to request clarification or add additional context in comments.

1 Comment

ty - guess that was my mistake
2

You need to use sort_by! in order to modify the original array.

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.