Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!