诗歌rails之 数组分组

关键字: rails in_groups_of
这次讲的是active_support/core_ext/array/grouping.rb里的in_groups_of方法
ruby代码
  1. #   %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}  
  2. #   ["1""2""3"]  
  3. #   ["4""5""6"]  
  4. #   ["7", nil, nil]  
  5. #  
  6. #   %w(1 2 3).in_groups_of(2' ') {|g| p g}  
  7. #   ["1""2"]  
  8. #   ["3"" "]  
  9. #  
  10. #   %w(1 2 3).in_groups_of(2false) {|g| p g}  
  11. #   ["1""2"]  
  12. #   ["3"]  
in_groups_of的第一个参数指示几个元素一组,而第二个参数指示了当最后一组缺元素时用什么填补位置
我们可以几个一组来显示tasks了:
ruby代码
  1. <table>  
  2. <% @tasks.in_groups_of(4,false) do |row_tasks| %>  
  3.   <tr>  
  4.     <% for task in row_tasks %>  
  5.       <td><%= task.name %></td>  
  6.     <% end %>  
  7.   </tr>  
  8. <% end %>  
  9. </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
posted @ 2009-07-08 10:29  麦飞  阅读(1011)  评论(0编辑  收藏  举报