Ruby min/max

I wondered why Ruby seemed to be missing min() and max() functions, which of course are very useful.
Turns out you’re supposed to use Enumerable.min and Enumerable.max like so:

irb(main):020:0> [2, 1].min
=> 1

4 Responses to “Ruby min/max”

  1. Jeremy Roush Says:

    Old post, but useful. Much appreciated!

  2. Rob Morris Says:

    I find the “official” version very counter-intuitive. My first thought, when coding up a comparison, is not to create a transient array.

    If you’re like me, throw this into your environment.rb or similar init code:

    module Math
    def self.min(a,b)
    a = b ? a : b
    end
    end

    Now you can do Math.min(1,2) and be a little more clear on what you’re doing. Cheers!

  3. Rob Morris Says:

    Sorry, got garbled, here’s another attempt:

    module Math
    def self.min(a,b)
    a <= b ? a : b
    end

    def self.max(a,b)
    a >= b ? a : b
    end
    end

  4. Raoul Duke Says:

    @module Math

    hm, does that properly handle floating point? like, is there any weirdness with negative zero?

Leave a Reply


http://www.canakkaleruhu.org http://www.vergimevzuati.org http://www.finansaldenetci.com http://www.securityweb.org http://www.siyamiozkan.org http://www.fatmaozkan.com http://www.sgk.biz.tr http://www.denetci.gen.tr http://www.bagimsizdenetim.biz.tr http://www.mevzuat.biz.tr http://www.security.biz.tr http://www.sorgulatr.com http://www.kanunlar.biz http://www.prsorgu.net http://www.sirabul.com http://www.emekliol.org http://www.coklupagerank.com http://www.coklupagerank.net http://www.coklupagerank.org http://www.prsorgu.org http://www.scriptencode.com http://www.sirabul.net http://www.sirabul.org http://www.sitenizanaliz.com http://www.seoisko.com http://www.seomavi.com http://www.scriptencode.net http://www.scriptencode.org