根据字符串中的数字对Ruby字符串数组进行排序

时间:2022-05-11 16:00:20

If I have a string array that looks like this:

如果我有一个像这样的字符串数组:

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

数组= ["STRING1", "STRING05", "STRING20", "STRING4", "STRING3"]

or

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

数组= ["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 }

sort_by {|k, v| -k}

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

我到处都找过了,但想不出解决办法

2 个解决方案

#1


13  

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

#2


2  

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

按每个字符串中的数字(降序)对数组进行排序

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

#1


13  

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

#2


2  

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

按每个字符串中的数字(降序)对数组进行排序

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