这次讲的是active_support/core_ext/array/grouping.rb里的in_groups_of方法
我们可以几个一组来显示tasks了:
- # %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
- # ["1", "2", "3"]
- # ["4", "5", "6"]
- # ["7", nil, nil]
- #
- # %w(1 2 3).in_groups_of(2, ' ') {|g| p g}
- # ["1", "2"]
- # ["3", " "]
- #
- # %w(1 2 3).in_groups_of(2, false) {|g| p g}
- # ["1", "2"]
- # ["3"]
# %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g} # ["1", "2", "3"] # ["4", "5", "6"] # ["7", nil, nil] # # %w(1 2 3).in_groups_of(2, ' ') {|g| p g} # ["1", "2"] # ["3", " "] # # %w(1 2 3).in_groups_of(2, false) {|g| p g} # ["1", "2"] # ["3"]
in_groups_of的第一个参数指示几个元素一组,而第二个参数指示了当最后一组缺元素时用什么填补位置
我们可以几个一组来显示tasks了:
- <table>
- <% @tasks.in_groups_of(4,false) do |row_tasks| %>
- <tr>
- <% for task in row_tasks %>
- <td><%= task.name %></td>
- <% end %>
- </tr>
- <% end %>
- </table>
<table> <% @tasks.in_groups_of(4) do |row_tasks| %> <tr> <% for task in row_tasks %> <td><%= task.name %></td> <% end %> </tr> <% end %> </table>
# File vendor/rails/activesupport/lib/active_support/core_ext/array/grouping.rb, line 22 22: def in_groups_of(number, fill_with = nil) 23: if fill_with == false 24: collection = self 25: else 26: # size % number gives how many extra we have; 27: # subtracting from number gives how many to add; 28: # modulo number ensures we don't add group of just fill. 29: padding = (number - size % number) % number 30: collection = dup.concat([fill_with] * padding) 31: end 32: 33: if block_given? 34: collection.each_slice(number) { |slice| yield(slice) } 35: else 36: returning [] do |groups| 37: collection.each_slice(number) { |group| groups << group } 38: end 39: end 40: end
关键字: split(value = nil) {|element| ...}
[1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]] (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
# File vendor/rails/activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results 101: end 102: end