0

I am getting an error I don't understand. It runs how I intended but throws an error at the end. I am still new to ruby but I know it has something to do with my for loops.

This is my code

nums = Array.new(24){Array.new(80){'X'}}
system('cls')
for i in 0..24
    for j in 0..79
            print nums[i][j]
    end
 end

And this is the error messages

K:/Ruby 2/RubyInvaders.rb:5:in block (2 levels) in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
from K:/Ruby 2/RubyInvaders.rb:4:in each'
from K:/Ruby 2/RubyInvaders.rb:4:in block in <main>'
from K:/Ruby 2/RubyInvaders.rb:3:in each'
from K:/Ruby 2/RubyInvaders.rb:3:in <main>'

Its ok to offer better ways to do this but I would also like to understand why I am getting this error

2 Answers 2

3

You are creating an array with 24 elements and then a loop with 25 iterations. When you try to print the 25th iteration of that loop, the array position doesn't exist. If you change for i in 0..24 to for i in 0..23, the error should be addressed:

nums = Array.new(24){Array.new(80){'X'}}
system('cls')
for i in 0..23
  for j in 0..79
    print nums[i][j]
  end
end

To amplify on Jon's comment, ruby ranges created with the ... operator are exclusive and won't use the highest specified value (as opposed to the .. operator, which is inclusive).

And--while your approach to looping is valid--it's not idiomatic for ruby. Something like this would be more common:

nums = Array.new(24){Array.new(80){'X'}}
system('cls')
(0..23).each do |i|
  (0..79).each do |j|
    print nums[i][j]
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

I see now. I have been staring straight at the problem but kept looking at the for loops and never checked my original declaration.
You could also use 0...24 and 0...80, which is a little easier to comprehend.
"creating" => "are creating", "of with" => "of", "and then create" => "creating"
3

When i is 24, nums[i] is nil, and you are calling [] on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.