Reputation: 909
I'm trying to print a value out of an array but for some reason can't. Here's my code:
click = rightClick(mat, sel) #(click is a method that opens an input window. It returns an array of 5 values)
constLib << click
constNum=constLib.length
for i in 0..constNum
puts (constLib[i][1])
end
I get an error saying:
Error: #<NoMethodError: undefined method `[]' for nil:NilClass>
(eval):37:in `block (4 levels) in initialize'
(eval):34:in `each'
(eval):34:in `block (3 levels) in initialize'
-e:1:in `call'
Any ideas?
Thanks!
Upvotes: 1
Views: 111
Reputation: 5693
If you have an array with 5 items, the first item in the array is item 0, and the last item is item 4.
e.g. 0,1,2,3,4
Your for loop needs to go from 0 to (constNum-1), or it needs to use the "..." exclusive operator instead of the inclusive "..".
However, you should consider going through the array using each
click = rightClick(mat, sel)
click.each do |item| {
puts item[0]
}
I've changed the puts to print the first item in the array. This may have been what you were tring to do. This is item[0], and not as I think you originally wrote, item[1].
Upvotes: 0
Reputation: 59232
..
is inclusive. Which means, you're accessing the out of bound index, that is the length of the array. Hence change it to ...
which is exclusive.
However, that's not how rubyists approach it, as they might frown upon you for using for loop. It's better to use each
constLib.each {|arr| puts arr[1]}
Upvotes: 3