# Get min or max from set of values

Are there any conventional ways, like with predefined functions, for getting the minimum or maximum value of a list; or, do I have to define that myself with something like this?

``````define :lesser do |a, b|
if a <= b then
return a
else
return b
end
end

define :min do |list|
low = list
list.each do |n|
if n < low then
low = n
end
end
return low
end
``````

Ruby has built in functions for this.

``````puts [3,5].min # => 3
puts [-4,-6].max # => -4
#also this
puts [1,-3,65,23].minmax # => [-3,65]
#you can have long lists in the first two rather than just comparing two values
``````

if you want you could define your own functions for this eg

``````define :minValue do |a,b|
return [a,b].min
end

define :maxValue do |a,b|
return [a,b].max
end

puts minValue(4,4.1)     # => 4
puts maxValue(4,4.1)     # => 4.1
``````
2 Likes

If this was SO, I wouldn’t leave a reply just to say “Thanks!”, but this seems like the polite thing to do. I really appreciate it!

2 Likes