Argh. Having trouble here trying to work out how to build my array in Ruby.
So I am looping through a result and I want to add the category field as the key and have it so that if the next row has the same category it gets put into that category. If not, it makes a new array and adds it to that.
Here is what I have so far.
data = Array.new
results.each do |row|
data[row.category].push row.field
end
Which is not going to work I know. I want data[row.category] to eventually be (after the loop) an array containing all the row.field‘s
So I end up with an array that looks like this.
[['Dogs', 5, 12, 2], ['Cats', 4, 5, 9], ['Fish', 25, 82, 23]]
So no matter how many loops I do, if I push it into an array that already exists in data then it just appends it, if the array doesn’t exist it creates it and then appends it.
In PHP I would simply do this:
$data[$row['category']][] = $row['field']
With the empty [] denoting to create a new array if there is none. How do I do this in Ruby???
Yeah, you seem to be confused by PHP and its associative arrays (which aren’t called arrays in any other language 🙂 ). You need a hash. Try this snippet: