Raj
Raj

Reputation: 22926

`sort_by': comparison of Array with Array 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 it fails:

custom_sorter.rb:17:in `sort_by': comparison of Array with Array failed (ArgumentError)

I know that nil might produce this error. But there is no nil in my data.

Upvotes: 27

Views: 20112

Answers (2)

Traian Svinti
Traian Svinti

Reputation: 133

Just noting as this caught me out for a couple of minutes. If your hash has both string and symbols as keys, this same error will occur and it's not entirely obvious.

Upvotes: 4

undur_gongor
undur_gongor

Reputation: 15954

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

The initial elements are booleans. There is no order defined for booleans.

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

You can get around this by creating integer values, e.g.

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

Upvotes: 46

Related Questions