<%
old_city = ""
@objects.order("city").each do |obj|
if old_city != obj.city && old_city != ""
old_city = obj.city
%>
--Different city--
<%
end
%>
City: <%= obj.city %>
<%
end
%>
So that output expected is:
Chicago
Chicago
--Different city--
New York
New York
New York
--Different city--
Paris
--Different city--
Rio de Janeiro
Maybe there’s some cleaver/different way to do that in rails?
I don’t think this is the best code for it…
Thanks!
There are several options, but
Enumerableoffers agroup_bymethod.group_bytakes a block to define groupings. After grouping it’s a matter of iterating over the resulting map’s keys.If you want to order by keys, you can do that too by sorting the keys and retrieving the resulting map’s values while iterating over the sorted keys.
If they’re
ActiveRecords you might want to do the work in SQL/ActiveRecordproper.