user273072545345
user273072545345

Reputation: 1566

How to write my own max function

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

Answers (2)

tokland
tokland

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

Arup Rakshit
Arup Rakshit

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) -

enter image description here

Upvotes: 2

Related Questions