oprogfrogo
oprogfrogo

Reputation: 2074

Iterating through hashes inside an array

I have a stored procedure that returns the following hashes inside of a single array:

@cars = [{"make"=>"honda"}, {"color"=>"black"}, {"make"=>"acura"}, {"color"=>"red"}]

How would I iterate through each of these so that I can correctly put them into tables. Resulting in:

<table>
  <tr>
    <td>honda</td>
    <td>black</td>
  </tr>
  <tr>
    <td>acura</td>
    <td>red</td>
  </tr>
</table>

Upvotes: 0

Views: 690

Answers (2)

Sam Ruby
Sam Ruby

Reputation: 4340

<table>
<% @cars.each_slice(2) do |hash1, hash2| %>
  <tr>
    <td><%= hash1['make'] %></td>
    <td><%= hash2['color'] %></td>
  </tr>
<% end %>
</table>

Upvotes: 1

cam
cam

Reputation: 14222

I would change the format of the data in ruby:

@good_cars = @cars.each_slice(2).map { |a,b| a.merge(b) }
# returns [{"make"=>"honda", "color"=>"black"}, {"make"=>"acura", "color"=>"red"}]

Upvotes: 2

Related Questions