1

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'
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • You have the answer already, but note that it would probably be easier to use `String#each_char` here, and avoid index shenanigans. – matthew.tuck Jan 17 '22 at 11:18

1 Answers1

2

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
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • Seems, like I have a ways to go on this journey. I know -1 usually grabs the last index in ruby (which is awesome.) Thats basically whats happening? It's evaluating if a == a making the if statement true. – ChronoKross Jan 16 '22 at 20:18
  • Correct. `str[0]` is `a` and `str[-1]` is `a`, so your conditional evaluates to `true` – Cjmarkham Jan 16 '22 at 20:22