2014-01-20 71 views
3

我需要在Ruby中對混合數組進行排序。它有Fixnum S和String小號如何使用混合字符串和Fixnums對Ruby數組進行排序

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' 

回答

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
a, b = [1, "cool", 3, "story", 4, "bro"].partition(&Fixnum.method(:===)) 
a.sort + b #=> [1, 3, 4, "cool", "story", "bro"] 
1

實際上,我總是需要先按Fixnum排序,然後再按String元素排序:

ar.sort_by { |n| n.to_s } # => [1, 3, 4, "bro", "cool", "story"] 

這僅一個元素轉換成塊內的字符串進行比較,但在它返回Fixnum對象的原始狀態

相關問題