我需要在Ruby中对混合数组进行排序。它有Fixnum
和String
s
ar = [1, "cool", 3, "story", 4, "bro"]
我希望Fixnum
s优先于字符串,而不关心字符串的顺序。
ar = [1,3,4,"cool","story","bro"]
我尝试为class Array
Class Array
def mixed_sort
self.sort do |a,b|
if a.class == Fixnum and b.class != a.class
-1
else
a <=> b
end
end
end
end
我想我可能只是将一个块传递给Array#sort
方法。但是,此方法在按下块之前仍然会抛出错误
[1] pry(main)> [1, "11", '12', 3, "cool"].mixed_sort
ArgumentError: comparison of String with 3 failed
from /config/initializers/extensions/array.rb:3:in `sort'
答案 0 :(得分:6)
我会使用Enumerable#grep
执行以下操作:
ar = [1, "cool", 3, "story", 4, "bro"]
ar.grep(Fixnum).sort + ar.grep(String)
# => [1, 3, 4, "cool", "story", "bro"]
如果您还想对字符串进行排序,请执行以下操作:
ar = [1, "cool", 3, "story", 4, "bro"]
ar.grep(Fixnum).sort + ar.grep(String).sort
# => [1, 3, 4, "bro", "cool", "story"]
答案 1 :(得分:1)
a, b = [1, "cool", 3, "story", 4, "bro"].partition(&Fixnum.method(:===))
a.sort + b #=> [1, 3, 4, "cool", "story", "bro"]
答案 2 :(得分:1)
实际上,我总是需要先按Fixnum排序,然后再按String元素排序:
ar.sort_by { |n| n.to_s } # => [1, 3, 4, "bro", "cool", "story"]
这只会将一个元素转换为块中的字符串以进行比较,但会返回其中的Fixnum的原始状态