Skip to content

Instantly share code, notes, and snippets.

@juanfurattini
Created July 2, 2021 02:58
Show Gist options
  • Save juanfurattini/2698144d3fc0fb76b22851f30bb1a3dd to your computer and use it in GitHub Desktop.
Save juanfurattini/2698144d3fc0fb76b22851f30bb1a3dd to your computer and use it in GitHub Desktop.
Second max number
def second_max_number(array)
raise 'Argument array must be an enumerable' unless array.is_a?(Enumerable)
raise 'Argument array must have at least 2 elements' if array.size < 2
max, second_max = nil
array.each do |current|
if max.nil? || (!current.nil? && current > max)
if second_max.nil? || (!max.nil? && max > second_max)
second_max = max
end
max = current
elsif second_max.nil? || (!current.nil? && current > second_max)
second_max = current
end
end
second_max
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment