Home > Mobile >  undefined method `<' for nil:NilClass error but no nil exists?
undefined method `<' for nil:NilClass error but no nil exists?

Time:04-12

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)

CodePudding user response:

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
  •  Tags:  
  • ruby
  • Related