Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

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

Ruby • Asked by Premila Anand

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

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

Thanks in advance!

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}}]

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

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

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

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

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.

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!

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.

  <% @array.each do |item| %>
      <td><%= item[:month] %></td>
      <% item[:years].each do |year| %>
        <td><%= year[1] %></td>
      <% end %>
  <% end %>

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

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


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 31,152+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.