Processing array of objects into two strings 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 &lt;&lt; item.particular
  amounts &lt;&lt; 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?
You can get by with just two lines:

particulars_string = items.map(&amp;:particular).join("\n")
amounts_string     = items.map(&amp;:amount).join("\n")


Enumerable#map, which is mixed into Array, creates a new array from an existing array by running a block on each element and storing the result. In this case though you don't need a full block, since you just need to call a single method (particular or amount). So it basically extracts those into new arrays and then joins those arrays.

As a rule of thumb, you almost never have to "manually" map stuff from one array to another in Ruby using each and &lt;&lt;. Be sure to read the docs for Array and Enumerable as they're full of good stuff.