Friday, February 8, 2013

Longest String

So I realized after I had made this spec using sort and max methods for the array that this was absolutely wrong and the only way that it passed the tests was because the longest array in the spec as "zzzzzzzzz". I then went back iterated over an array with a variable max to find the longest array and then return the result as a string. I did have to use Boolean logic as I did not take into account if the array is empty like this array == []. Once I was able to put that in this passed the test right away. I can definitely refactor this because it is very long, but I really want to get into the space of coding something out and flowing with it and refactoring afterwords. I will do the shortest string again because that was not correctly done as well and post it as well. Until then....stay thirsty my friends.


  1. def longest_string(array)
  2.   max = 0
  3.   result = ''
  4.   if array == []
  5.     return nil
  6.   else
  7.     array.each do |x|
  8.       if x.length > max
  9.         max = x.length
  10.         result = x
  11.       else
  12.       end
  13.     end
  14.     result
  15.   end
  16. end

No comments:

Post a Comment