简体   繁体   English

如何对字符串和整数数组进行排序以首先在 ruby​​ 中显示排序的整数

[英]how to sort an array of strings and integers to show sorted integers first in ruby

I have an array containing integer values and string type characters as such _我有一个包含整数值和字符串类型字符的数组,例如_

Here is my array array = ["_", 2, 3, "_"] how can I sort them such that it returns like the following: [2, 3, "_", "_"] I have tried to sort it with the ruby .sort() method but it appears as if sort() does not compare integers with strings and therfore returns an error.这是我的数组array = ["_", 2, 3, "_"]我如何对它们进行排序,使其返回如下所示: [2, 3, "_", "_"]我试图排序它使用 ruby .sort()方法,但看起来sort()不将整数与字符串进行比较,因此返回错误。

is there a ruby method I am not aware of?有没有我不知道的 ruby​​ 方法? Any help or guidance is highly appreciated.非常感谢任何帮助或指导。

The problem is you can't compare a string to an integer:问题是您无法将字符串与整数进行比较:

> 2<"2"
(irb):15:in `<': comparison of Integer with String failed (ArgumentError)

The fix (with your specific example) is to make array act as if it is all strings.修复(使用您的特定示例)是使array表现得好像它是所有字符串。

Given:鉴于:

array = ["_", 2, 3, "_"]

If you just want the result to be a uniform string array:如果您只希望结果是一个统一的字符串数组:

> array.map{|e| e.to_s}.sort
=> ["2", "3", "_", "_"]

If you want the elements to maintain their type:如果您希望元素保持其类型:

> array.map{|e| [e.to_s, e]}.sort.map{|e| e[1]}
=> [2, 3, "_", "_"]

Or, alternatively:或者,或者:

> array.sort_by{|e| e.to_s}
=> [2, 3, "_", "_"]

The potential issue here is that if you rely solely on a conversion to a string (which solved the example you gave) you will get a bad result with integers:这里的潜在问题是,如果您仅依赖于字符串的转换(它解决了您给出的示例),您将得到整数的错误结果:

> array = ["10", 12, 3, "0", "b", "a"]
=> ["10", 12, 3, "0", "b", "a"]
> array.sort_by{|e| e.to_s}
=> ["0", "10", 12, 3, "a", "b"]   # desirable?

Which is not entirely solvable by using .to_i :使用.to_i不能完全解决:

> array.sort_by{|e| e.to_i}
=> ["0", "b", "a", 3, "10", 12]   # fixed?

Which maybe is best solved by sorting on both:最好通过对两者进行排序来解决:

> array.sort_by{|e| [e.to_i, e.to_s]}
=> ["0", "a", "b", 3, "10", 12]

Luckily Ruby makes it super easy to choose.幸运的是,Ruby 使它非常容易选择。


Note, .sort_by or the other enumerable sorts are not a stable sort so elements that compare equal are potentially returned in different order than given:请注意, .sort_by或其他 可枚举的排序不是稳定的排序,因此比较相等的元素可能以与给定顺序不同的顺序返回:

> array=[1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
> array.sort_by{|e| 0}  # make them all compare equal 
=> [9, 2, 3, 4, 5, 6, 7, 8, 1]

To fix that now, add an index:现在要解决这个问题,请添加一个索引:

> array.each_with_index.sort_by{|e,i| [0,i]}.map(&:first)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Or, as pointed out in comments:或者,正如评论中指出的那样:

> array.sort_by.with_index { |e, i| [0, i] }
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM