按整数值对字符串数组进行排序 [英] Sort an Array of Strings by their Integer Values

查看:51
本文介绍了按整数值对字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个从 1 到 10 的未排序数组,如下所示...

Let's say I have an unsorted array from 1 to 10, as shown below...

a = ["3", "5", "8", "4", "1", "2", "9", "10", "7", "6"]

如果我在这个数组上使用 sort 方法,它会返回这个...

If I use the sort method on this array, it returns this...

a.sort = ["1", "10", "2", "3", "4", "5", "6", "7", "8", "9"]

如您所见,10 出现在 2 之前,这是不正确的.如何对这些数字进行排序,以便 10 正确显示?

As you can see, the 10, appears before the 2, which is incorrect. How can I sort these numbers so that 10 appears correctly?

谢谢大家的回复.我应该更好地解释我的问题.我需要排序的数组用于电子商务价格表.于是数组出现如下...

Thank you all for your responses. I should explain my problem a little better. The array I need sorted is for an e-commerce price list. So the array appears as follows...

a = ["0-10", "11-20", "21-30", "31-40" etc.]

所以字符串不能转换为整数.当我写这个问题时,我应该把这个写出来.我不认为修复会有太大差异.我的错误,我为做出这个假设而道歉!我怎样才能对这个数组进行排序?谢谢!

So the strings cannot be converted to integers. I should have put this when I wrote the question. I did not think that there would be much difference in the fix. My mistake, I apologise for making this assumption! How though can I sort this array? Thanks!

推荐答案

我会抛出另一种方法,因为这是我能想到的最短方法

I'll throw another method out there since it's the shortest way I can think of

a.sort_by(&:to_i)

这篇关于按整数值对字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆