arr = [2,4,6,8]
i = 0
while i < arr.length do
puts arr[i + 1] - arr[i]
i = i + 1
end
It puts out the values on the console but also issues an error
ERROR (on RubyMine 7): C:\Ruby21\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/.../file/application.rb 2 2 2 C:/Users/inoor/RubymineProjects/file/application.rb:4:in
<top (required)>': undefined method
-' for nil:NilClass (NoMethodError) from -e:1:inload' from -e:1:in
'Process finished with exit code 1
Can someone please help me understand what's going on?
Whenever you see the nil:NilClass (NoMethodError)
error in ruby you should look for whatever objects could have become nil
. In your case, you are iterating over an array and are hitting an edge case.
Let's look at your code in detail:
# Start with this array of length 4
arr = [2,4,6,8]
# Initilize counter to 0
i = 0
# Run this loop while i < 4
while i < arr.length do
puts arr[i + 1] - arr[i]
# Increment by 1 each time
i = i + 1
end
The case you are running into the nil
object is at the very end. When i=3
, i+1=4
and you are trying to access the index 4 element in your array. Remember, arrays in ruby (like most languages) are 0-indexed. So your array has indexes 0,1,2, and 3. If you attempt to access an index that you haven't defined a value for, ruby will return nil
. So arr[4]
,arr[400]
, and arr[100000000]
all return the same thing: nil
.