在Ruby 1.8.6中,我有一个数组,比如100,000个用户id,每个用户id都是一个int.我想在这些用户ID上执行一段代码,但我想以块的形式执行.例如,我想一次处理100个.我怎样才能尽可能简单地实现这一目标?
我可以做类似下面的事情,但可能有一个更简单的方法:
a = Array.new
userids.each { |userid|
a << userid
if a.length == 100
# Process chunk
a = Array.new
end
}
unless a.empty?
# Process chunk
end
Run Code Online (Sandbox Code Playgroud) 我需要一种方法将数组拆分为另一个大小相等的数组中的一堆数组.有人有任何方法吗?
例如
a = [0, 1, 2, 3, 4, 5, 6, 7]
a.method_i_need(3)
a.inspect
=> [[0,1,2], [3,4,5], [6,7]]
Run Code Online (Sandbox Code Playgroud) 我有一个类似这样的数组:
arr = [4, 5, 6, 7, 8, 4, 45, 11]
Run Code Online (Sandbox Code Playgroud)
我想要一种奇特的方法
sub_arrays = split (arr, 3)
Run Code Online (Sandbox Code Playgroud)
这应该返回以下内容: [[4, 5, 6], [7,8,4], [45,11]]
Note: This question is not a duplicate of "How to chunk an array" The chunk question is asking about processing in batches and this question is about splitting arrays.
可能重复:
如何将Ruby数组拆分(块)成X个元素的部分?
我想将一个数组拆分成一个子数组.
例如,
big_array = (0...6).to_a
Run Code Online (Sandbox Code Playgroud)
我们如何将这个大数组切割成一个数组(最大长度为2项)的数组,例如:
arrays = big_array.split_please(2)
Run Code Online (Sandbox Code Playgroud)
哪里...
arrays # => [ [0, 1],
[2, 3],
[4, 5] ]
Run Code Online (Sandbox Code Playgroud)
注意:我问这个问题,'因为为了做到这一点,我目前编码如下:
arrays = [
big_array[0..1],
big_array[2..3],
big_array[4..5]
]
Run Code Online (Sandbox Code Playgroud)
......太难看了.而且非常难以维护的代码big_array.length > 100.
我需要将3个结果包装在不同的div中.我将使用基本查询返回结果:
@items = Item.all
Run Code Online (Sandbox Code Playgroud)
但在视图中,我需要以3块为单位列出结果:
<% @items.each do |item| %>
<div>
<p>Result 1</p>
<p>Result 2</p>
<p>Result 3</p>
</div>
<div>
<p>Result 4</p>
<p>Result 5</p>
<p>Result 6</p>
</div>
Run Code Online (Sandbox Code Playgroud)
等等...
任何帮助从ROR菜鸟赞赏
我有一个大型数组,我想将其均匀地分成n个数组.
我尝试使用each_slice,但只根据传递给它的数字参数将数组切成小部分.
我怎样才能做到这一点?