Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by highest value calculated from contents

I have an array of strings like this:

["Brazil (62)", "PalestinianTerritoryOccupied (6)", "Macedonia (2)", "Germany (6)"]

I want to sort them by the highest value but it's got me stumped. I've tried all sorts of weird, wonderful (and useless) things like:

cont.sort! { |it| it.scan(/\d+/).to_s.to_i}
like image 532
facetoe Avatar asked Feb 01 '12 16:02

facetoe


People also ask

How do I sort the contents of an array?

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.

How do you sort an array of objects based on a property?

Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.

How do you sort an array in ascending order?

Example: Sort an Array in Java in Ascending Order Then, you should use the Arrays. sort() method to sort it. That's how you can sort an array in Java in ascending order using the Arrays. sort() method.

How do you sort an array by object value?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


1 Answers

sort_by {|e| e[/\d+/].to_i }.reverse

should do the trick. You can write this one in a more efficient and elegant way (see comments), like in the following:

sort_by {|e| -e[/\d+/].to_i }

Note the -.

Using sort you can do:

sort {|a, b| b[/\d+/].to_i <=> a[/\d+/].to_i }

EDIT

String#[] has been suggested in the comments.

like image 94
lucapette Avatar answered Oct 17 '22 07:10

lucapette