Support for nil values in Enumerable.min or max

Posted by admin, Thu Sep 06 06:55:44 UTC 2007

My build failed today, after I added some new code to find the min and max value from inside a Hash.  My hash was keeping track of x,y pairs, and I needed to find the min and max of the x’s.

min = data_series.min {|a,b| a[1][0] <=> b[1][0] } max = data_series.max {|a,b| a[1][0] <=> b[1][0] } Looks pretty simple. But sometimes, I had nil values for the x’s. At which point you get treated to the, not very descriptive, error message:
ArgumentError: comparison of Array with Array failed

I tried a few things like:

min = data_series.min {|a,b| a[1][0] <=> b[1][0] unless a[1][0].nil? or b[0][1].nil? }

But that didn’t work either. After some Googling, and reading some documentation for a completely different Enumerable method, the answer occurred to me. The block CAN’T return nil. It has to return one of the Comparable values of -1, 0, or 1. So:

min = data_series.min {|a,b| (a[1][0].nil? or b[1][0].nil?) ? 0 : a[1][0] < => b[1][0] }

And, finally, that worked. The lesson learned here is that the block versions of max and min MUST return -1, 0, or 1. Remember that next time, Lori.

Filed Under: | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.