诗歌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"]  
 # %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了:
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>  
<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

转载于:https://www.cnblogs.com/orez88/articles/1518945.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值