ruby Rails 3.2 遍历数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11355820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:15:42  来源:igfitidea点击:

Rails 3.2 iterate through an array

rubyarraysruby-on-rails-3.1hashiteration

提问by ctilley79

I have an array that looks like this:

我有一个看起来像这样的数组:

@shipment_products
[
  {"old_qty_shipped"=>"324", "product_id"=>"1", "qty_shipped"=>"12443"}
  {"old_qty_shipped"=>"4343423", "product_id"=>"3", "qty_shipped"=>"321344"}
  {"old_qty_shipped"=>"23", "product_id"=>"4", "qty_shipped"=>"321"}
]

I want to end up being able to do something like this

我希望最终能够做这样的事情

@shipment_products.each do |p|
  Product.adjust_qtys(p.old_qty_shipped, p.qty_shipped, p.product_id)
end

I'm getting the following error

我收到以下错误

NoMethodError (undefined method `qty_shipped' for #<ActiveSupport::HashWithIndifferentAccess:0x007f>)

The array is not quite in the right format to do this. I need to find a way to be able to iterate through the key/values and extract the attributes so I can call the method I created in the model. Any ideas?

该数组的格式不太适合执行此操作。我需要找到一种方法来遍历键/值并提取属性,以便我可以调用我在模型中创建的方法。有任何想法吗?

回答by Shamith c

Check following code.

检查以下代码。

   @shipment_products = [ {"old_qty_shipped"=>"324", "product_id"=>"1", "qty_shipped"=>"12443"}, {"old_qty_shipped"=>"4343423", "product_id"=>"3", "qty_shipped"=>"321344"} , {"old_qty_shipped"=>"23", "product_id"=>"4", "qty_shipped"=>"321"}]

    @shipment_products.each do |p|
      Product.adjust_qtys(p['old_qty_shipped'], p['qty_shipped'], p['product_id'])
    end