0

I want to make an array of hashes. But the problem is after first iteration when code goes to next line then it directly replaces the content of array.

@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

This is what i am getting after first iteration suppose i have this data

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

As soon as next line is executed it directly changes @item_name(name variable) After executing item[:name] = Invoiceinfo.find(@invoiceinfo.id).item.name the content of the @item_name is changed

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

Any help would be appreciated. Thannks

1
  • There's a good answer, but to clarify what you're doing wrong you're just reassigning the value to the same keys over and over. Commented Jan 22, 2017 at 13:59

2 Answers 2

4

Try something like this

@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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, i was not re-initializing the hash.
Exactly. And I made one SQL query for iteration, not three :) You're welcome
Good to see you provided the third line of code as a bonus.
4

If you consider using ruby paradigms and best practices in ruby code, this mistake won’t happen in the future.

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.