rubybyebug

ruby help me trace the outcome


How come the outcome to this is 'a' the if statement should completely be skipped tbh (it's falsey?). ? Being there is no str[i-1] on the first iteration, it should throw an error, but it doesn't? When i trace through the steps using ByeBug it does throw an error.. which I don't understand.

lib/test.arb:6:in longest_streak': undefined method status' for [nil, nil, nil, nil, "s"]:Array (NoMethodError) from lib/test.arb:19:in `'

def longest_streak(str)

    current = ''

    longest = ''

    (0...str.length).each do |i|
        if str[i] == str[i - 1]
            current += str[i]
        end
        if current >= longest
            longest = current
        end
    end
    longest
end

p longest_streak('a')           # => 'a'

Solution

  • In Ruby, a negative index will traverse backwards. So str[-1] will go from the end of the array, which will be a since that's the only character in the array.

    str[-1] and str[0] are the same thing in this instance, which is why the if condition is evaluated, because i is only ever 0 and 0 - 1 == -1.

    You could work around this by adding a check to your conditional

    if !(i - 1).negative? && str[i] == str[i - 1]
      current += str[i]
    end