Home > Mobile >  Ruby/Rails Iterating Array of Hashes
Ruby/Rails Iterating Array of Hashes

Time:10-30

I have a table that is getting populated from an Array of Hashes. The data looks like this:

[
  {'key' => 'some key', 'value' => 'some value'}, 
  {'key' => 'some key2', 'value' => 'some value2'},
  {'key' => 'some key3', 'value' => 'some value3'},
  {'key' => 'some key4', 'value' => ''},
  {'key' => 'some key5', 'value' => ''}
]

But it can also look like this:

[
  {'key' => 'some key', 'value' => ''}, 
  {'key' => 'some key2', 'value' => ''},
  {'key' => 'some key3', 'value' => ''}
]

What's happening now is that the data where the values are all empty strings is rendering rows on my view. I don't want to render a row if ALL the values are empty strings. If the values have at least one non-empty string, I do want to render that row.

How can I stop the rendering of a row if ALL the values are empty strings? I've tried iterating through the data, which sort of works. This code:

<% @data.each do |r| %>
  <tr>
    <% r.each do |h| %>
      <% unless h['value'].empty? %>
        <td><%= h['value'] %></td>
      <% end %>
    <% end %>
  </tr>
<% end %>

stops rendering the rows where all values are empty, but it also doesn't render the <td> where the row has some values that are empty because it's not rendering those <td>.

CodePudding user response:

You need to check all the values of the « columns » of your « row » before starting to render the « row »

<% @data.each do |r| %>
  <% unless r.all? { |h| h["value"].empty? } %>
  <tr>
    <% r.each do |h| %>
        <td><%= h['value'] %></td>
    <% end %>
  </tr>
  <% end %>
<% end %>
  • Related