views:

38

answers:

3

Hi!

I'm looking for a function we can use in a loop to do this:

<% for rink in @rinks_in_region %>  
    <%= rink.city #Show Only if city (n-1) != n %> 
    <%= link_to_rink(rink.name+" Ice Rink",rink) %>
    <br>
<% end -%>

Basically just show the city only if it's different than the previous one.

Make sense? Thanks for your help!

Alextoul

A: 
<% prev_city = nil -%>
<% for rink in @rinks_in_region %>
    <%= rink.city if rink.city != prev_city %>
    <% prev_city = rink.city -%>
    <%= link_to_rink(rink.name+" Ice Rink",rink) %>
    <br>
<% end -%>
Pär Wieslander
A: 

Not a ruby answer, but introduce a new variable, call it 'temp' or something and set that to the current element in your foreach. That way at the beginning of your loop you have access to last loops element.

temp = ''
    <% for rink in @rinks_in_region %>  
        <%= rink.city #Show Only if city != temp %> 
        <%= link_to_rink(rink.name+" Ice Rink",rink) %>
        <br>

temp = city

    <% end -%>

temp = ''
tilman
Sorry for pseudo code, not a ruby programmer ;)
tilman
I see what you mean, thks a lot
Alextoul
+4  A: 

You could use the group_by method on @rinks_in_region to group rinks by city and then use those groupings to display cities and rinks. It returns a hash mapping the thing you are grouping by, city in this case, to the values in the original collection that are in that group. So:

<% @rinks_in_region.group_by(&:city).each_pair do |city, rinks| %>  
  <%= city %> 
  <% rinks.each do |rink| %>
    <%= link_to_rink(rink.name+" Ice Rink",rink) %>
    <br/>
  <% end -%>
<% end -%>
Shadwell
Beerlington
Very good point. Updated.
Shadwell
First time I hear of this group_by method. Awesome stuff. +1
Faisal
Amazing! Thanks a lot!
Alextoul