<div dir="ltr">Hi LRUG - hopefully an interesting little problem:<br><br>I have an Event class which has an "expected_date" attribute.<br>Some events don't have an expected date, so like a good little OO programmer i've created a Null object:<br><br><div>class NoExpectedDate</div><div> def to_s(format=:default)</div><div> "Unknown"</div><div> end</div><div>end</div><div><br></div><div>This works great for printing the values, but when it comes to sorting the list I of course get:<br>
ArgumentError: comparison of Date with NoExpectedDate failed <br><br>If I include Comparable and define <=> then one comparison works, but the other doesn't :<br><br><div>class NoExpectedDate</div><div> include Comparable</div><div> def to_s(format=:default)</div><div> "Unknown"</div><div> end</div><div> def <=>(other_date)</div><div> 1 # Treat it as after every other date</div><div> end</div><div>end</div></div><div>
<p class=""><span class="">$ </span><span class="">NoExpectedDate</span><span class="">.new > </span><span class="">Date</span><span class="">.today<br></span><span class="">=> </span><span class="">true</span></p>
<p class=""><span class="">$ </span><span class="">Date</span><span class="">.today > </span><span class="">NoExpectedDate</span><span class="">.new<br></span>ArgumentError: comparison of Date with NoExpectedDate failed<br><br>I think this is because Date's <=> method expects it's argument to be a Date object or a number ("a numeric value as an astronomical Julian day number"). I've tried defining to_i and to_r on NoExpectedDate, but no dice.<br><br>Can I get NoExpectedDate to pretend to be a Date (like SimpleDelegator lies about it's class)? Is that evil?<br><br>I suppose I could always just define a method on Event to do this particular sort, but that seems nasty for all sorts of reasons:<br><br></p><p class="">def sort_by_expected_date sort do |a, b| </p><p class=""> if b.class = NoExpectedDate </p><p class=""> 1</p><p class=""> else</p><p class=""> a <=> b</p><p class=""> end</p><p class=""> end</p><p class="">end</p><p class=""><br></p></div></div>