Matt-Lepley
Matt-Lepley

Reputation: 71

How to get previous item in each loop

I have a SQL query that loads information into a hash. I want to iterate through that information and output it into the view.

If the user_id is the same as the previous object's user_id, I don't want to display that user_id, just the name and everything else. It seems like the logic should be simple, but being a novice at Ruby and Rails, I'm not sure what is really available to do this.

I was trying something like this, but prev_id was never getting updated after the first iteration:

<% @session.each_with_index do |s, x| %>
    <% if x == 0 then prev_id = 'nil' end %>
    <% curr_id = s['id'] %>


    <% if curr_id != prev_id %>
        <%= s['id'] %>
    <% end %>

    <%= s['name'] %>
    <%= s['count'] %><br>
    <% prev_id = curr_id %>
<% end %>

Any help is greatly appreciated!

Upvotes: 1

Views: 3394

Answers (2)

sawa
sawa

Reputation: 168249

You should use chunk.

<% @session.chunk{|s| s["id"]}.each do |curr_id, a| %>
  <%= curr_id %>
  <% a.each do |s| %>    
    <%= s["name"] %>
    <%= s["count"] %><br>
  <% end %>
<% end %>

Upvotes: 3

sjagr
sjagr

Reputation: 16512

You have to declare your prev_id outside of the loop for it to persist between iterations:

<% prev_id = nil %>
<% @session.each_with_index do |s, x| %>
    <% if x == 0 then prev_id = 'nil' end %>
    <% curr_id = s['id'] %>


    <% if curr_id != prev_id %>
        <%= s['id'] %>
    <% end %>

    <%= s['name'] %>
    <%= s['count'] %><br>
    <% prev_id = curr_id %>
<% end %>

Upvotes: 3

Related Questions