sort_by: array to array comparison failed (no nil data)

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)

But he fails:

custom_sorter.rb: 17: in `sort_by ': the array was not compared with the array (ArgumentError)

I know nil can produce this error. But in my data there is no bottom.

+4
source share
1 answer

When the sorting algorithm compares the created arrays [Time.now <= cs.start_date, (cs.available || 0)], it compares them by elements.

The source elements are Boolean. There is no order for booleans.

irb(main):001:0> true <=> false
=> nil

You can get around this by creating integer values, for example.

[cs1, cs2, cs3, cs4, cs5].sort_by { |cs| [Time.now <= cs.start_date ? 0 : 1, (cs.available || 0)] }
+14
source

Source: https://habr.com/ru/post/1616030/


All Articles