I have an array of Item objects that each have a string particular and a numeric amount. I want to put all particulars (separated by newlines) into a single string and the same for all amounts.
Here's what I came up with:
particulars = []
amounts = []
items.each do |item|
particulars << item.particular
amounts << item.amount
end
particulars_string = particulars.join("\n")
amounts_string = amounts.join("\n")
So if
item1.particular = "food"
item2.particular = "drink"
item1.amount = 1000
item2.amount = 2000
then running the code above gives
particulars_string # "food\ndrink"
amounts_string # "1000\n2000"
which is correct. However, I feel that the above code can be done better. In particular, I want all the code in one loop, not the three (each and two joins) I have now. What's a better way to do this?