Skip to content

Commit 1b16b7c

Browse files
committed
Longest String and edited Max
1 parent 2abdd47 commit 1b16b7c

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

exercises/longest_string.rb

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,25 @@
1212
# str.length == 4
1313

1414
def longest_string(list)
15-
# This is your job. :)
15+
my_long_str = list[0] # assigns a varible to the first array index
16+
list.each do |str| # for each str in list
17+
if str.length > my_long_str.length # if the lengthof current str is greater than my_long_str
18+
my_long_str = str # set str to my_long_str
19+
end
20+
end
21+
return my_long_str
1622
end
1723

24+
# A far better and shorter solution (on StackOverflow) is my_long_str = list.max_by(&:length)
25+
# But I will stick with my own homegrown solution
26+
27+
1828
if __FILE__ == $PROGRAM_NAME
1929
# I'd advise putting some sanity checks here.
2030
# How else will you be sure your code does what you think it does?
31+
32+
p longest_string(["We", "might", "have", "missed", "a", "corner", "case"]) == "missed"
33+
p longest_string(["Remember", "that", "conceptually", "x"]) == "conceptually"
34+
35+
p longest_string([123456789, "might", "have", 23564.25689, "a", "corner", "case"]) == "corner"
2136
end

exercises/max.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def max(list)
6161
# prints out "true."" For example,
6262
# 1. We might have missed a corner case
6363
# 2. The code does what it should, but is conceptually confused
64-
# 3. Something else we haven't though of
64+
# 3. Something else we haven't thought of
6565
#
6666
# Remember: Option #3 is *always* possible.
6767
#

0 commit comments

Comments
 (0)