0

In a Ruby app, I have an array that may contain instances of the Ruby Date class and instances of my MissingDate class.

Now, I need to get the min (or have sort working) from the array. So, I'm looking for the method I need to define in the MissingDate class in order to make min work but that proofs to be more difficult than anticipated.

Any ideas?

Sig
  • 5,476
  • 10
  • 49
  • 89
  • Please clarify "to make `min` work". Do you want to simply determine the earliest date, disregarding `MissingDate` objects? – Cary Swoveland Apr 26 '21 at 16:30

2 Answers2

0

According to the documentation you need to implement Comparable.

In your MissingDate include Comparable and define the spaceship operator (<=>).

Kamil Gwóźdź
  • 777
  • 5
  • 11
0

You simply want to extract the Date objects and then find the earliest.

require 'date'
class MissingDate
end
arr = [Date.parse("17 Apr 21"), MissingDate.new, Date.parse("1 Jan 21"),
       MissingDate.new, Date.parse("31 Mar 21")]
arr.grep(Date).min
  #=> #<Date: 2021-01-01 ((2459216j,0s,0n),+0s,2299161j)>

If arr contains no Date objects nil is returned.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100