在Ruby中对字符串和数字进行排序 [英] Sort strings and numbers in Ruby

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

问题描述

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

I want to sort an array by strings first and then numbers. How do I do this?

推荐答案

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

A general trick for solving tricky sorts is to use #sort_by, with the block returning an array having the primary and secondary sort order (and, if you need it, tertiary, etc.)

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#定义< => 方法:

This works because of the way array comparison is defined by Ruby. The comparison is defined by the Array#<=> method:

以元素方式"比较数组;使用< =>运算符将ary的第一个元素与other_ary的第一个元素进行比较,然后再对每个第二个元素进行比较,依此类推…只要任何此类比较的结果都不为零(即两个对应的元素不为等于),则返回的结果将用于整个数组比较.

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中对字符串和数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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