class CustomSorter attr_accessor :start_date,:available def initialize(start_date,available) @start_date = Time.mktime(*start_date.split('-')) @available = available end end cs1 = CustomSorter.new('2015-08-01',2) cs2 = CustomSorter.new('2015-08-02',1) cs3 = CustomSorter.new('2016-01-01',1) cs4 = CustomSorter.new('2015-02-01',3) cs5 = CustomSorter.new('2015-03-01',4) sorted = [cs1,cs2,cs3,cs4,cs5].sort_by { |cs| [Time.now <= cs.start_date,(cs.available || 0)] } puts sorted.map(&:start_date)
但它失败了:
custom_sorter.rb:17:in `sort_by’: comparison of Array with Array Failed (ArgumentError)
解决方法
当排序算法比较创建的数组[Time.now< = cs.start_date,(cs.available || 0)]时,它会逐元素地对它们进行比较. 最初的元素是布尔值.没有为布尔定义订单.
irb(main):001:0> true <=> false => nil
你可以通过创建整数值来解决这个问题.
[cs1,cs5].sort_by { |cs| [Time.now <= cs.start_date ? 0 : 1,(cs.available || 0)] }