每天一剂Rails良药之Easily Group Lists of Things

今天看看两个很好用的方法
1,Enumerable#group_by():
<%
  employees = Employee.find(:all).group_by{|employee|
    employee.title
  }
%>
<% employees.each do |title, people| %>
  <h2><%= title %></h2>
  <ul>
    <% people.each do |person| %>
      <li><%= person.name %></li>
    <% end %>
  </ul>
<% end %>


2,Array#in_groups_of()
<table class="calendar">
  <% (1..DAYS_IN_MARCH).to_a.in_groups_of(7) do |group| %>
    <tr>
      <% group.each do |day| %>
        <td><%= day %></td>
      <% end %>
    </tr>
  <% end %>
</table>

Array#in_groups_of()可以有第二个参数,当一个group的某几个为空时值为该参数,否则为nil

你可能感兴趣的:(Rails)