0

I have a simple array

my_array = [{id:1,priority_score:2},{id:3,priority_score:5},{id:4,priority_score:3.5}...]

I am trying to sort by the priority score with

sort_array = my_array.sort_by{|priority| priority[:priority_score]}

strangely, I am not getting a back any difference from my original array.

I create the priority score using

new_hash = {id:h.id,priority_score:(a.score+b.score)/2}

and have added all sorts of .to_f,.to_i in case the problem was that the priority score was not being recognized as a number, but that isn't the problem.

Any suggestions?

1

3 Answers 3

1

you can use sort_by like this.

my_array.sort_by {|(h, _)| h[:priority_score]}
# [{:id=>1, :priority_score=>2}, {:id=>4, :priority_score=>3.5}, {:id=>3, :priority_score=>5}]
Sign up to request clarification or add additional context in comments.

3 Comments

I haven't seen the _ before, what is that for? (I left the office, so i can't actually check this until tomorrow).
_ means not caring value. a, _ = [10, 20] it will set a to 10.
@pedalpete I reexamined my answer and it is wrong. edu's solution is correct. my_array.sort_by {|h| h[:priority_score]} and my solution same thing. may you remove accept I'll delete it.
1

The Array#sort method takes a block with two arguments, a and b, and wants you to compare them by hand. Given how you invoke it, I think you wanted sort_by, which takes a block with each item in the array, performs some transformation, and sorts by the result.

1 Comment

thanks Daniel, I typed it wrong, i am using sort_by, corrected my question now. sorry for that.
1

The sort gets two elements and the sorting is done by the comparison result of these elements.

This comparison should return -1, 0, 1.

0 for equal, -1 first < second and +1 first > second.

In most of the cases you can use ruby built in function <=>

For example:

my_array = [{id:1,priority_score:2},{id:3,priority_score:5},{id:4,priority_score:3.5}]

# Sort ascending  
cr = my_array.sort {|a,b| a[:priority_score] <=> b[:priority_score]}
#[{:id=>1, :priority_score=>2}, {:id=>4, :priority_score=>3.5}, {:id=>3, :priority_score=>5}]

# Sort descending
de = my_array.sort {|a,b| b[:priority_score] <=> a[:priority_score]}
#[{:id=>3, :priority_score=>5}, {:id=>4, :priority_score=>3.5}, {:id=>1, :priority_score=>2}]

1 Comment

thanks Edu, I typed the question wrong, I am using sort_by. sorry for the confusion, but thanks for explaining this so clearly.

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.