Sort the array by the largest value calculated from the contents

I have an array of such lines:

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

I want to sort them by the highest value, but it puzzled me. I tried all kinds of weird, wonderful (and worthless) things like:

cont.sort! { |it| it.scan(/\d+/).to_s.to_i} 
+4
source share
1 answer
 sort_by {|e| e[/\d+/].to_i }.reverse 

gotta do the trick. You can write this in a more efficient and elegant way (see Comments), as in the following:

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

Pay attention to - .

With sorting, you can:

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

EDIT

Line # [] was suggested in the comments.

+6
source

Source: https://habr.com/ru/post/1394223/


All Articles