哈希数组会直接将数据覆盖到数组

时间:2017-01-22 13:54:21

标签: ruby-on-rails ruby hash

我想制作一系列哈希。但问题是在第一次迭代后代码转到下一行然后它直接替换数组的内容。

@item_name =[]
item = {}
@invoiceinfo.each do |invoice|
  item[:name] =  Invoiceinfo.find(@invoiceinfo.id).item.name
  item[:desc] =  Invoiceinfo.find(@invoiceinfo.id).desc
  item[:unit_price] =  Invoiceinfo.find(@invoiceinfo.id).unit_price
  byebug
  @item_name.push (item)
end

这就是我得到的 在第一次迭代后假设我有这个数据

@item_name = [{:name=>"usman", :desc=>"sample ", :unit_price=>100}]

一旦执行下一行,它就会直接更改@item_name(名称变量) 执行item[:name] = Invoiceinfo.find(@invoiceinfo.id).item.name @item_name 的内容已更改

  

@item_name = [{:name =>“next_name”,:desc =>“sample”,:unit_price => 100}]

任何帮助将不胜感激。 Thannks

2 个答案:

答案 0 :(得分:4)

尝试这样的事情

@item_name = []
@invoiceinfo.each do |invoice|
  invoice_info = Invoiceinfo.find(@invoiceinfo.id)

  item = {}
  item[:name] =  invoice_info.item.name
  item[:desc] =  invoice_info.desc
  item[:unit_price] = invoice_info.unit_price

  @item_name.push(item)
end

答案 1 :(得分:4)

如果你考虑在ruby代码中使用ruby范例和最佳实践,将来不会发生这种错误。

@item_name = @invoiceinfo.each_with_object([]) do |invoice, acc|
  invoice_info = Invoiceinfo.find(@invoiceinfo.id)

  acc.push(
    name: invoice_info.item.name,
    desc: invoice_info.desc
    unit_price: invoice_info.unit_price
  )
end