Bernardo Mendes
Bernardo Mendes

Reputation: 1220

Rails/Ruby ordering / splitting it

<% 
  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!

Upvotes: 0

Views: 68

Answers (2)

Marek Př&#237;hoda
Marek Př&#237;hoda

Reputation: 11198

Try something like this in the console:

Event.order(:city).group_by(&:city)

This will return a hash where the keys will be the individual cities and the values will be arrays of the corresponding event objects. You can then easily iterate over the hash's keys, and in an inner loop, iterate over the corresponding event objects.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160191

There are several options, but Enumerable offers a group_by method.

group_by takes a block to define groupings. After grouping it's a matter of iterating over the resulting map's keys.

objs = [
  { :foo => 'baz', :wat => 'kthxbai' },
  { :foo => 'bar', :wat => 'narnar' },
  { :foo => 'plugh', :wat => 'xyzzy' },
  { :foo => 'bar', :wat => 'ohai' },
  { :foo => 'baz', :wat => 'fuuuu' },
  { :foo => 'plugh', :wat => 'jimmies' }
]

grouped = objs.group_by { |o| o[:foo] }
grouped.each do |k, v|
  puts "GROUP: #{k}"
  v.each { |v| puts v }
end

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/ActiveRecord proper.

Upvotes: 1

Related Questions