forked from codeunion/ruby-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_string.rb
35 lines (32 loc) · 1000 Bytes
/
longest_string.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Method name: longest_string(list)
# Inputs: a list of strings
# Returns: the longest string in the list
# Prints: Nothing
#
# For example, longest_string(["a", "zzzz", "c"]) should return "zzzz" since
# the other strings are 1 character long and "zzzz" is 4 characters long.
#
# Ties go to the earliest word in the list.
#
# To get the length of a string in the variable str, call str.length
# For example,
# str = "zzzz"
# str.length == 4
def longest_string(list)
longest = list.first
list.each do |current_str|
if current_str.length > longest.length
longest = current_str
end
end
longest
end
if __FILE__ == $0
p longest_string(["a","zzzz","c"]) == "zzzz"
p longest_string(["hello","goodbye","hola"]) == "goodbye"
p longest_string(["a","b","c"]) == "a"
p longest_string(["a"]) == "a"
p longest_string(["hello"]) == "hello"
p longest_string(["supercalafragilicious","superawesome","super"]) == "supercalafragilicious"
p longest_string([""]) == ""
end