Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby-添加到多维数组_Ruby On Rails_Ruby_Multidimensional Array - Fatal编程技术网

Ruby on rails Ruby-添加到多维数组

Ruby on rails Ruby-添加到多维数组,ruby-on-rails,ruby,multidimensional-array,Ruby On Rails,Ruby,Multidimensional Array,我希望循环一个进程,每次都向数据库添加一个对象,但如果添加不正确,我希望在多维数组中收集错误。一个数组将保留发生错误的批次,第二个数组将显示错误消息 这是我的声明: errors = [[],[]] 因此,我希望数组的格式如下: [[lot_count, "#{attribute}: #{error_message}" ]] 在循环之后应该是这样的: [[1, "Name: Can not be blank" ],[1, "Description: Can not be blank" ],[

我希望循环一个进程,每次都向数据库添加一个对象,但如果添加不正确,我希望在多维数组中收集错误。一个数组将保留发生错误的批次,第二个数组将显示错误消息

这是我的声明:

errors = [[],[]]
因此,我希望数组的格式如下:

[[lot_count, "#{attribute}: #{error_message}" ]]
在循环之后应该是这样的:

[[1, "Name: Can not be blank" ],[1, "Description: Can not be blank" ],[2, "Name: Can not be blank" ]]
我的问题是它无法将其添加到数组中。我不确定多维数组的语法是否不同

这在我的数组中什么都没有

errors.push([[lot_count, "#{attribute}: #{error_message}" ]])
这也没有给我数组中的任何内容

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

推送时,阵列嵌套得太深:

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

你可以从一个空数组开始

errors = []
…然后构建单个错误数组

e = [lot_count, "#{attribute}: #{error_message}" ]
。。。并将其推到错误数组的末尾

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

由于内部数组中似乎总是有相同类型的信息,因此最好使用的数组是,例如
Struct.new(“DBError”,:count,:attribute,:message)
。然后,您可以创建结构并使用
错误推送它们,这只是一个观察,但哈希映射可能是执行此操作的更节省内存的方法。类似于Rails的ActiveModel::Errors[。或者可能是Set[因为散列和一些数组功能也会给内存带来很多好处。我在如何声明多维数组方面弄错了,谢谢!
[[1, "Name: Can not be blank" ],[1, "Description: Can not be blank" ],[2, "Name: Can not be blank" ]]