简体   繁体   中英

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}" ]]

It appears you nest your arrays too deep when pushing:

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

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" ]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM