[LRUG] Comparable Null Objects

Frederick Cheung frederick.cheung at gmail.com
Wed Jul 15 05:17:02 PDT 2015




On 15 July 2015 at 13:03:21, Duncan Stuart (dgmstuart at gmail.com) wrote:

$ NoExpectedDate.new > Date.today
=> true

$ Date.today > NoExpectedDate.new
ArgumentError: comparison of Date with NoExpectedDate failed

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.

Can I get NoExpectedDate to pretend to be a Date (like SimpleDelegator lies about it's class)? Is that evil?



I think this is what coercion is for (e.g. http://www.mutuallyhuman.com/blog/2011/01/25/class-coercion-in-ruby/ )


Fred

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:


def sort_by_expected_date sort do |a, b| 

    if b.class = NoExpectedDate 

      1

    else

      a <=> b

    end

  end

end



_______________________________________________  
Chat mailing list  
Chat at lists.lrug.org  
Archives: http://lists.lrug.org/pipermail/chat-lrug.org  
Manage your subscription: http://lists.lrug.org/options.cgi/chat-lrug.org  
List info: http://lists.lrug.org/listinfo.cgi/chat-lrug.org  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20150715/bfdc5309/attachment.html>


More information about the Chat mailing list