[英]Ruby - Adding on to a Multidimensional Array
我想遍歷一個過程,每次都將一個對象添加到我的數據庫中,但是如果添加不正確,我想將錯誤收集在多維數組中。 一個陣列將保留發生錯誤的批次,第二個陣列將顯示錯誤消息。
這里是我的報關表:
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)
這將給您您的最終結果
[[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.