Skip to content

Instantly share code, notes, and snippets.

@FioFiyo
Created June 21, 2016 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FioFiyo/a1d6539b0b18059a172ba7dae650f418 to your computer and use it in GitHub Desktop.
Save FioFiyo/a1d6539b0b18059a172ba7dae650f418 to your computer and use it in GitHub Desktop.
Using inject to replace max method as opposed to using loops to replace that method.
# Find the maximum
def maximum(arr)
arr.inject {|max,num| max = num > max ? num : max}
end
# expect it to return 42 below
result = maximum([2, 42, 22, 02])
puts "max of 2, 42, 22, 02 is: #{result}"
# expect it to return nil when empty array is passed in
result = maximum([])
puts "max on empty set is: #{result.inspect}"
result = maximum([-23, 0, -3])
puts "max of -23, 0, -3 is: #{result}"
result = maximum([6])
puts "max of just 6 is: #{result}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment