ruby - 在 Ruby 中对字符串和数字进行排序

标签 ruby sorting

我想先按字符串对数组进行排序,然后再按数字对数组进行排序。我该怎么做?

最佳答案

解决棘手排序的一般技巧是使用#sort_by,该 block 返回具有主要和次要排序顺序的数组(如果需要,还可以返回第三等)

a = ['foo', 'bar', '1', '2', '10']  
b = a.sort_by do |s|
  if s =~ /^\d+$/
    [2, $&.to_i]
  else
    [1, s]
  end
end
p b    # => ["bar", "foo", "1", "2", "10"]

之所以可行,是因为 Ruby 定义了数组比较的方式。比较由 Array#<=> 定义方法:

Arrays are compared in an “element-wise” manner; the first element of ary is compared with the first one of other_ary using the <=> operator, then each of the second elements, etc… As soon as the result of any such comparison is non zero (i.e. the two corresponding elements are not equal), that result is returned for the whole array comparison.

关于ruby - 在 Ruby 中对字符串和数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1955646/

相关文章:

ruby - 在 ruby​​ 中测试线程代码

r - 使用 dplyr 在组内安排

java - 我的排序算法有名称吗?

c# - 如何从合并排序中获得O(n log(n))?

Ruby Shoes 不适用于符号

ruby - 如何创建退出消息

html - Bootstrap 表单样式不适用

ruby-on-rails - 如果我们事先不知道它们的存在,是否可以识别实例变量?

sorting - 对任何类型的列表进行快速排序 | haskell

c - 冒泡排序不适用于大文件,但适用于小文件