Reputation: 545
I'm trying to program a method that would loop through a 2d array and return the coordinates of the elements that comply with a given condition (in this case, element value == 1
):
def eval(array)
array.each_index do |x|
x.each_index do |y|
if array[x][y] == 1 then
puts "X: #{x} Y: #{y}"
end
end
end
end
array = [
[1, 0, 0, 0],
[0, 1, 0, 0],
[1, 0, 0, 1],
[0, 1, 0, 0]
]
eval(array)
I'm getting this error:
block in eval': undefined method `each_index' for 0:Fixnum (NoMethodError)
Any tips on what might be happening?
Upvotes: 2
Views: 171
Reputation: 403
array.each_index do |x|
captures this index into x variable and then you are trying to use each_index on number. Namely
x.each_index do |y|
Fixing this issue gives us the function:
def findMatchingCords(array)
array.each_index do |x|
array[x].each_index do |y|
if array[x][y] == 1 then
puts "X: #{x} Y: #{y}"
end
end
end
end
Now findMatchingCords(array) yields
X: 0 Y: 0
X: 1 Y: 1
X: 2 Y: 0
X: 2 Y: 3
X: 3 Y: 1
as expected.
Upvotes: 4
Reputation: 110745
You could make use of the Matrix class.
require 'matrix'
def evaluate(array)
Matrix[*array].each_with_index { |e,x,y| puts "X: #{x} Y: #{y}" if e == 1 }
end
evaluate(array)
X: 0 Y: 0
X: 1 Y: 1
X: 2 Y: 0
X: 2 Y: 3
X: 3 Y: 1
Upvotes: 1