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 => 1Sphere: Related Content
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 => 1Sphere: Related Content
November 8th, 2007 at 2:36 am
Old post, but useful. Much appreciated!
May 9th, 2008 at 9:11 am
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!
May 9th, 2008 at 9:12 am
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