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
Sphere: Related Content

3 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

Leave a Reply

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click on the image to regenerate some new text.

Anti-Spam Image