user3127502
user3127502

Reputation: 153

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

Upvotes: 8

Views: 7635

Answers (2)

bjhaid
bjhaid

Reputation: 9782

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"]

Upvotes: 23

xdazz
xdazz

Reputation: 160973

sort the array by the number in each string (descending)

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

Upvotes: 3

Related Questions