Skip to content

Instantly share code, notes, and snippets.

@kmandreza
Created January 3, 2013 04:33
Show Gist options
  • Save kmandreza/4440818 to your computer and use it in GitHub Desktop.
Save kmandreza/4440818 to your computer and use it in GitHub Desktop.
Write a method largest_integer which takes as its input an Array of integers and returns the largest integer in the Array. For example: largest_integer([-10, 0, 10]) # => 10 largest_integer([-10, -20, -30]) # => -10
# largest_integer is a method that takes an array of integers as its input
# and returns the largest integer in the array
#
# +array+ is an array of integers
# largest_integer(array) should return the largest integer in +array+
#
# If +array+ is empty the method should return nil
#using sort will go through the array a bunch of times, which is less efficient
def largest_integer(array)
array.sort.last
end
#OR...I can use the each method and it will go through the array once. Below is a better way to do it.
def largest_integer(array)
max = nil
array.each do |x|
if max.nil? || max < x
max = x
end
end
max
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment