這裏有一個方法,使「橙色」,「黃」,「藍」是在每個陣列中的任何位置,並且每個數組可能不包含這些三種顏色中的一些或全部。使用給定的字符串排序對每個數組以及包含數組進行排序。正常陣列排序適用,因此,如果每兩個陣列的第一個元素是相同的,所述第二元件相比較,等等
我暫時重新定義String#<=>,然後以通常的方式排序,然後在返回之前恢復String#<=>
。
代碼
def reorder(arr)
String.send(:alias_method, :old_compare, :<=>)
String.class_eval do
define_method(:<=>) do |other|
order = ["Blue", "Yellow", "Orange"] # increasing priority
self_ndx = order.index(self) || -1
other_ndx = order.index(other) || -1
other_ndx <=> self_ndx
end
end
a = arr.map(&:sort).sort
String.send(:alias_method, :<=>, :old_compare)
String.send(:undef_method, :old_compare)
a
end
實例
reorder [["Red", "Blue"], ["Green", "Orange"], ["Purple", "Yellow"]]
#=> [["Orange", "Green"], ["Yellow", "Purple"], ["Blue", "Red"]]
reorder [["Blue", "Orange"], ["Purple", "Green"], ["Purple", "Orange"]]
#=> [["Orange", "Blue"], ["Orange", "Purple"], ["Purple", "Green"]]
reorder [["Yellow", "Orange"], ["Orange", "Orange"], ["Blue", "Yellow"]]
#=> [["Orange", "Orange"], ["Orange", "Yellow"], ["Yellow", "Blue"]]
reorder [["Yellow", "Purple"], ["Purple", "Orange", "Blue"], ["Blue", "Yellow"]]
#=> [["Orange", "Blue", "Purple"], ["Yellow", "Blue"], ["Yellow", "Purple"]]
歡迎SO。寫得很好的問題。非常簡潔。 – 2014-10-12 03:44:51