1

We have array of arrays: matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]

Now, calling

matrix.each do |x| 
  print x
end

returns the three arrays as I would expect ([0, 1, 1, 2][0, 5, 0, 0][2, 0, 3, 3]).

But when doing

matrix.each do |x| 
    if x.include?(0)
        z_index = x.index(0)
        for zero in z_index
            for x in matrix do
                matrix[i].delete_at(zero)
                i+=1
            end
        end
    else
        next
    end
end

I get undefined method 'each' for 0:Integer, which means each is picking up the 0 in the first nested array, instead of picking up the entire first nested array. Why is it behaving this way?

6
  • 1
    No way. The error is induced. Commented Sep 25, 2018 at 10:52
  • 1
    Show #do something here code it has each loop Commented Sep 25, 2018 at 10:54
  • Added the full code. There are two more iterations, but they are for loops, not each. Commented Sep 25, 2018 at 11:02
  • 1
    for zero in z_index is the issue. z_index is obviously 0 there. FYI: any iteration uses each under the hood in ruby. Also, we don’t use for loops in ruby, it’s considered a code smell. Commented Sep 25, 2018 at 11:11
  • Sidenote: you shouldn’t delete elements from the currently iterated array. Commented Sep 25, 2018 at 11:14

1 Answer 1

2

When you do

for zero in z_index 

This is effectively

z_index.each do |zero|

The in part of a for in loop has to be something you can iterate over (an array)

z_index is the first element of x which is the first element of matrix so it contains an integer.

Sign up to request clarification or add additional context in comments.

4 Comments

Right! I was expecting each to grab the elements regardless of the number (1 or 100). Why doesn't that work? What's the alternative if in the next loop there is more than 1 element in the array?
If you want to iterate over the elements, maybe what you wanted to do was for zero in x but can you explain what you expect the code to do? I don't see i is initialized before use, by the way, so that' going to be a problem further on.
Yes, I didn't paste the whole method here. z_index can have 1 or multiple elements. In the case of 1 element I run into the mentioned error. Is there a neat way of handling 1 element scenario? Or should I just go with if else statement?
z_index CANNOT have one or multiple elements, it can only have nil (if there's no element 0) or it can have the index of the first occurence of 0, which in your examples happens to be 0. If you want an array of all the index positions of 0 you should do z_index = x.each_with_index.map{|x,i| x.zero? ? i : nil}.compact

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.