字符串和数字混合的数组如何排序?
数组是字符串和数字混合的array01
=> ["zero", "one", "two", "three", "dos", "tre", 0, 10, 2]
直接sort排序失败。
irb(main):057:0> array01.sort
ArgumentError: comparison of String with 2 failed
from (irb):57:in `sort'
from (irb):57
from /usr/bin/irb:12:in `<main>'
求问如何做? 你预期是什么样的结果呢?
>> a = ["zero", "one", "two", "three", "dos", "tre", 0, 10, 2]
=> ["zero", "one", "two", "three", "dos", "tre", 0, 10, 2]
>> a.sort_by {|i| i.to_s}
=>
>> a.sort_by {|i| i.to_i}
=> ["zero", "one", "two", "three", 0, "tre", "dos", 2, 10]
回复 2# Sapien
多谢。!!!! Sapien回复滴挺快的。 回复Sapien
多谢。!!!!
laohuanggua 发表于 2010-12-27 02:03 http://bbs.chinaunix.net/images/common/back.gif
不用sort_by也可以:
irb(main):024:0> a
=> ["zero", "one", "two", "three", "dos", "tre", 0, 10, 2]
irb(main):025:0> a.map{|s| }.sort{|x,y| x<=>y}.map{|e| e}
=> 不用sort_by也可以:
zuerrong 发表于 2010-12-28 12:34 http://bbs.chinaunix.net/images/common/back.gif
这个,有点绕远路了啊。
>> a
=> ["zero", "one", "two", "three", "dos", "tre", 0, 10, 2]
>> a.sort { |x,y| x.to_s <=> y.to_s }
=>
用这个效率比 sort_by 低,每次两两比对的时候2个元素都要执行一遍 to_s,而前者每个元素只需执行一遍 to_s。 这个,有点绕远路了啊。用这个效率比 sort_by 低,每次两两比对的时候2个元素都要执行一遍 to_s, ...
Sapien 发表于 2010-12-28 13:04 http://bbs.chinaunix.net/images/common/back.gif
不是绕远路,sort_by内部就是这么实现的,不过是用C实现的,看ruby cookbook. Ruby的方法实现,本来就像Perl一样,甚至比Perl还多。
页:
[1]