简体   繁体   English

Ruby-添加到多维数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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