patternrubyMinor
Processing array of objects into two strings
Viewed 0 times
objectsarrayintotwoprocessingstrings
Problem
I have an array of
Here's what I came up with:
So if
then running the code above gives
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 (
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 = 2000then 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?Solution
You can get by with just two lines:
As a rule of thumb, you almost never have to "manually" map stuff from one array to another in Ruby using
particulars_string = items.map(&:particular).join("\n")
amounts_string = items.map(&: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 <<. Be sure to read the docs for Array and Enumerable as they're full of good stuff.Code Snippets
particulars_string = items.map(&:particular).join("\n")
amounts_string = items.map(&:amount).join("\n")Context
StackExchange Code Review Q#39268, answer score: 4
Revisions (0)
No revisions yet.