user1977840
user1977840

Reputation:

Ruby - Adding on to a Multidimensional Array

I would like to loop through a process and add an object to my Database each time, but if it is not added properly I would like to collect the errors in a multidimensional array. One array would keep which Lot it was that had the error and the second array will have the error message.

Here is my declaration:

errors = [[],[]]

So I would like the array to be formatted like this:

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

Which should look like this after looping:

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

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

This gives me nothing in my array

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

This also gives me nothing in my array

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

Upvotes: 5

Views: 10929

Answers (2)

Thomas Klemm
Thomas Klemm

Reputation: 10856

You could start with an empty array...

errors = []

...then build the single error array...

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

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

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

This will give you your end result

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

Upvotes: 3

berkes
berkes

Reputation: 27553

It appears you nest your arrays too deep when pushing:

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

Upvotes: 3

Related Questions