Skip to content

Instantly share code, notes, and snippets.

@kmelkon
Created September 4, 2013 09:16
Show Gist options
  • Save kmelkon/6434652 to your computer and use it in GitHub Desktop.
Save kmelkon/6434652 to your computer and use it in GitHub Desktop.
@grouped = {}
Deal.all.each do |deal|
letter = deal.background.slice(0,1).upcase
@grouped[letter] ||= []
@grouped[letter] << deal
end
@DouweM
Copy link

DouweM commented Sep 4, 2013

<% @grouped.sort.each do |letter, deal| -%>
  <%= deal.background %>
<% end %>

Calling #sort on a Hash will turn it into a nested array:

{"b" => "x", "a" => "y"}.sort
# => [["a", "y"], ["b", "x"]]

Fortunately #each is smart enough to still support .each do |first_value_in_nested_array, second_value_in_nested_array| on that array, so the loop will just work like it's a Hash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment