ruby - Beginner array iteration & error code interpretation -
i kept getting following error. after research assumed because array access throwing error due (mistakenly) having nil value.
my_solution.rb:24:in `count_between': undefined method `>=' nil:nilclass (nomethoderror) my_solution.rb:35:in `<main>'
i'm new reading error codes, perhaps that's went wrong. got tunnel vision on line 24, error suggested. couldn't fix it, out of desperation wound randomly changing (<=) on line 23 (<). fixed it.
why did fix it? guess using (<=) made iterate "too far" , somehow returned nil?
why did error code element on line 24 causing issue, when element on line 23? i'm new , trying less intimated error codes, curious experience.
thanks guidance.
# count_between method 3 arguments: # 1. array of integers # 2. integer lower bound # 3. integer upper bound # # returns number of integers in array between lower , upper # bounds, # including (potentially) bounds. # # if +array+ empty method should return 0 # solution below: def count_between(list_of_integers, lower_bound, upper_bound) if list_of_integers.empty? return 0 else count = 0 index = 0 ##line 23## while index <= list_of_integers.length ##line24## if list_of_integers[index] >= lower_bound && list_of_integers[index] <= upper_bound count += 1 index += 1 else index += 1 end end return count end end puts count_between([1,2,3], 0, 100)
the last index that's <= list_of_integers.length
outside of array, since first index of array 0 , last array.length - 1
.
the reason error says line 24 line 23 works fine --- computes value of index
less or equal the length of array. once try , reference element @ index in array, however, it's assigned nil - , can't perform >=
operation on nil.
one thing might helpful here firing irb. if try reference element that's out of bounds, you'll nil. if try , perform operation (that's not listed in nil.methods
) on same reference, it'll throw error you're seeing.
Comments
Post a Comment