Skip to content

Instantly share code, notes, and snippets.

@dstavis
Created December 15, 2013 23:12
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 dstavis/7979684 to your computer and use it in GitHub Desktop.
Save dstavis/7979684 to your computer and use it in GitHub Desktop.
Exercise 19: Finding the longest string in an array
# longest_string is a method that takes an array of strings as its input
# and returns the longest string
#
# +array+ is an array of strings
# longest_string(array) should return the longest string in +array+
#
# If +array+ is empty the method should return nil
def longest_string(array)
return nil if array.empty?
longest_length = 0
array.each |string|
longest_length = string.length if string.length > longest_length
end#each
array.each |string|
if string.length == longest_length
longest_string = string
end#if
end#each
return longest_string
end#def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment