Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I iterate over an array of nested hashes in a view?

Premila Anand asked in Ruby

I have an array that has nested hashes of months, years and amounts that I want to diplay in a table. My data is in this format:

[{:month=>"January", :years=>{2017=>20, 2018=>100, 2019=>300}}, {:month=>"February", :years=>{2017=>30, 2018=>40, 2019=>80}}]

I want to display it in a table that looks like this:

Month 2017 2018 2019
January
February
March...

I am a beginner and am really struggling to access the values for the invidual years.

Thanks in advance!

Reply

Hi Premila,

In your views controller, you'll want to do something like:

def index # or whatever method you're working with
  @array = [{:month=>"January", :years=>{2017=>20, 2018=>100, 2019=>300}}, {:month=>"February",
:years=>{2017=>30, 2018=>40, 2019=>80}}]
end

then in your view, you'll do something like:

<% @array.each do |item| %>
  <ul>
    <li><%= item[:month] %> <%= item[:years] %></li>
  </ul>
<% end %>
Reply

Oh wait, are you needing them to be like this:

| Month | 2017 | 2018 | 2019 |
| --- | --- | --- | --- |
| January | 20 | 100 | 300 |
| February | 30 | 40 | 80 |

Reply

Ah boo, markdown isn't parsing the table - either way I think you see what I mean... lol 1 moment let me re-work with the table method in mind.

Reply

Yes, that's the table I'm trying to make! I'm able to display the months, but I get stuck with the years and values. Thank you for your help!

Reply

Here you go - trick is to remember that even though it's nested, it can still be iterated over inside another iteration... it helps to use byebug, so when I got to the part of getting the year values to display, I just placed <% byebug %> right below <% item[:years].each do |year| %> so I could then see how the objects are being presented and adjust as necessary.

<table>
  <tr>
    <th>Month</th>
    <th>2017</th>
    <th>2018</th>
    <th>2019</th>
  </tr>
  <% @array.each do |item| %>
    <tr>
      <td><%= item[:month] %></td>
      <% item[:years].each do |year| %>
        <td><%= year[1] %></td>
      <% end %>
    </tr>
  <% end %>
</table>
Reply

I was making it much harder. Good point on using byebug. I should have done that. Thank you for your help!!

Reply

Haha, making it harder is the easy part - making it easy is the hard part :)

Anytime!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.