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

257
Views
undefined method `<' for nil:NilClass error but no nil exists?

Was wondering why I get the error: "undefined method `<' for nil:NilClass" when compiling. After looking for reasons why, I found that you cannot use [] on an object with nil as a value. This makes sense, but I don't see why my array would contain nil in it. What am I missing?

   def binary_search(n, arr)
  middle = arr.length #pick middle value
  i = 0
  j = arr.length - 1

  while i <= j
    if arr[middle] == n
      return true
    elsif arr[middle] < n
      i = middle + 1
      middle = (i + j) / 2
    else
      j = middle - 1
      middle = (i + j) / 2
    end
  end
  false
end

nums = [76,32,50,90,10,8,15,49]
nums.sort
puts nums.inspect
binary_search(50, nums)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Let's look at a simplified subset of the code:

arr = [76,32,50,90,10,8,15,49]
middle = arr.length # 8
arr[middle] < 50 # NoMethodError
  • The length is 8.
  • arr[8] is nil, because there is no item at index 8. Remember that Ruby indexes begin with 0.
  • nil < 50 is a NoMethodError
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!