Reputation: 1566
I know that there is a max function from the Enumerable library in Ruby.
However, I'm trying to figure out how to write my own max method in which the largest number in an array is figured out.
How do I do that? I'm really at loss because when I Google it, all I keep getting is the max function itself.
Any help/advice would be helpful!
Upvotes: 4
Views: 868
Reputation: 67900
You have 2 approaches: Enumerable#each
(imperative) or Enumerable#reduce
(usually functional, depends on how you use it). I prefer functional solutions, so I'd write:
module Enumerable
def my_max
reduce { |current_max, x| x > current_max ? x : current_max }
end
end
Upvotes: 2
Reputation: 118289
Another naive approach is -
list = [3,4,2,5,6,7,8,2,5,1,4,4,6]
def maximum(list)
len = list.size - 1
maximum = list[0]
for i in 1..len
if maximum < list[i]
maximum = list[i]
end
end
maximum
end
puts maximum(list)
# >> 8
Here is the graphical explanation(taken from this link) -
Upvotes: 2