Our Daily Method #12: Comparable#at_least

Geplaatst door Michiel de Mare wo, 20 feb 2008 08:00:00 GMT

It took me a while before I discovered the accepted Ruby idiom to find the bigger of two values. I expected a method in Kernel or perhaps in Comparable. Instead, the Ruby Way is to create an array and ask the maximum value in the array:


[x,y].max
Well, it’s certainly short, but I don’t like it, for three reasons:
  • You create an array to compare two integers? That has to be inefficient, right? Of course, worrying about efficiency is not The Ruby Way.
  • I don’t like the name. When I say max it feels as if I’m declaring an upper bound, a maximum, when in fact, I’m declaring a lower bound, a minimum.
  • By listing both values in the array, you’re placing them on equal footing, when often that’s not really the case. Often it’s more an afterthought: you’re saying: I want value foo (and by the way, it must be at least 7.25).
Hence, at_most and at_least:

total_time / total_tries.at_least(1)

Implementation too trivial to list.

Geplaatst in , ,  | geen reacties

Reacties

(Laat url/e-mail achter »)

   Voorvertoning