简体   繁体   中英

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>

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"}]
<table>
<% @cars.each_slice(2) do |hash1, hash2| %>
  <tr>
    <td><%= hash1['make'] %></td>
    <td><%= hash2['color'] %></td>
  </tr>
<% end %>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM