I have a set of 2 or more objects that I’d like to order. I had been doing it like this:
card.max_by{|strength| strength.score
Where score was an integer score I had computed given some arbitrary rules. I knew this would be something I would refactor, so now I am doing so. And the “clean” way to give a score to a hand is to give it an array of values like
foo.score = [9,3,nil,4]
And compare it to another hand which might have an array like
bar.score = [5,10,12,12]
And foo <=> bar would tell me that foo is the greater array and so it should be returned by max_by. The problem is that max_by apparently won’t make comparisons on arrays. Is there another way I can do this to sort by the array value?
If it’s just array-based ordering that you want (you really do want the spaceship operator) and you want to find the ‘biggest’ by sorting, then:
If you really only need to find the largest hand, however, the following will be more efficient than ordering the entire array:
Edit: Reading your comment, if you really need multiple values that match, I would do this:
For an
inject-based implementation: