Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Ruby String Array by the number in the string

If I have a string array that looks like this:

array = ["STRING1", "STRING05", "STRING20", "STRING4", "STRING3"]

or

array = ["STRING: 1", "STRING: 05", "STRING: 20", "STRING: 4", "STRING: 3"]

How can I sort the array by the number in each string (descending)?

I know that If the array consisted of integers and not strings, I could use:

sort_by { |k, v| -k }

I've searched all around but can't come up with a solution

like image 360
user3127502 Avatar asked Mar 18 '14 00:03

user3127502


People also ask

How do you sort a string array in Ruby?

In Ruby, it is easy to sort an array with the sort() function. When called on an array, the sort() function returns a new array that is the sorted version of the original one.

How do you sort an array by value in Ruby?

You can use sort_by with a block, and one argument, to define one attribute for each object which is going to be used as the basis for sorting (array length, object attribute, index, etc.). The block should return an integer value which determines the position of the object in the sorted array.

How do you sort an array of strings?

To sort an array of strings in Java, we can use Arrays. sort() function.

How do I sort an integer into a string?

Convert each element in the String array obtained in the previous step into an integer and store in into the integer array. The sort() method of the Arrays class accepts an array, sorts the contents of it in ascending order. Sort the integer array using this method.


1 Answers

The below would sort by the number in each string and not the string itself

array.sort_by { |x| x[/\d+/].to_i }
=> ["STRING: 1", "STRING: 2", "STRING: 3", "STRING: 4", "STRING: 5"]

descending order:

array.sort_by { |x| -(x[/\d+/].to_i) }
=> ["STRING: 5", "STRING: 4", "STRING: 3", "STRING: 2", "STRING: 1"]
like image 91
bjhaid Avatar answered Sep 17 '22 20:09

bjhaid