Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
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'
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda