Ruby - adding to a multidimensional array

I would like to execute a loop and add an object to my database every time, but if it is not added correctly, I would like to collect errors in a multidimensional array. One array will save which lot it had, and the second array will have an error message.

Here is my expression:

errors = [[],[]] 

So, I would like the array to be formatted as follows:

 [[lot_count, "#{attribute}: #{error_message}" ]] 

What should look like this after the loop:

 [[1, "Name: Can not be blank" ],[1, "Description: Can not be blank" ],[2, "Name: Can not be blank" ]] 

My problem is that it will not add it to the array. I'm not sure if the syntax is different for a multidimensional array.

It gives me nothing in my array

 errors.push([[lot_count, "#{attribute}: #{error_message}" ]]) 

It also gives me nothing in my array

 errors += [[lot_count, "#{attribute}: #{error_message}" ]] 
+4
source share
2 answers

It looks like you nested your arrays too deep when pressed:

 errors.push([lot_count, "Foo:Bar"]) # => [[], [], [1, "Foo:Bar"]] 
+4
source

You can start with an empty array ...

 errors = [] 

... then create a single array of errors ...

 e = [lot_count, "#{attribute}: #{error_message}" ] 

... and push it to the end of the error array.

 errors << e # or errors.push(e) 

This will give you the final result.

 [[1, "Name: Can not be blank" ],[1, "Description: Can not be blank" ],[2, "Name: Can not be blank" ]] 
+3
source

All Articles