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
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
This entry was posted on Friday, November 10th, 2006 at 3:48 am and is filed under Ruby. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
ProjectX Technology is powered by WordPress with White as Milk
designed by Azeem Azeez. Entries (RSS) and Comments (RSS).
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
February 20th, 2009 at 8:15 pm
@module Math
hm, does that properly handle floating point? like, is there any weirdness with negative zero?