ruby-on-rails - 将 ruby​​ 数组的元素划分为精确数量的(几乎)大小相等的子数组

标签 ruby-on-rails ruby arrays ruby-1.8.7

<分区>

我需要一种方法来将数组拆分为精确数量且大小大致相等的较小数组。谁有办法做到这一点?

例如

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 
groups = a.method_i_need(3)
groups.inspect
    => [[1,2,3,4,5], [6,7,8,9], [10,11,12,13]]

Note that this is an entirely separate problem from dividing an array into chunks, because a.each_slice(3).to_a would produce 5 groups (not 3, like we desire) and the final group may be a completely different size than the others:

[[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13]]  # this is NOT desired here.

在这个问题中,预先指定了所需的 block 数,每个 block 的大小最多相差1。

最佳答案

您正在寻找 Enumerable#each_slice

a = [0, 1, 2, 3, 4, 5, 6, 7]
a.each_slice(3) # => #<Enumerator: [0, 1, 2, 3, 4, 5, 6, 7]:each_slice(3)>
a.each_slice(3).to_a # => [[0, 1, 2], [3, 4, 5], [6, 7]]

关于ruby-on-rails - 将 ruby​​ 数组的元素划分为精确数量的(几乎)大小相等的子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12374645/

相关文章:

ruby-on-rails - 用于 ruby​​/ruby on rails 的 SOAP 客户端生成器

ruby - 解码 YAML 序列化对象

c# - 在 C# 中将十进制数组转换为字节数组,反之亦然

c - 如何使用 fwrite 将指针数组的内容写入文件?

C++ 用数组简单计算分数

ruby-on-rails - 如何从heroku备份sqlite3

ruby-on-rails - 方法 width 和 height Mechanize

ruby - 在不总是指定模块的情况下访问常量

ruby-on-rails - Rspec 与 TestUnit

javascript - 我怎样才能逃脱并删除“;”?从 Rails 提供的数据到 JavaScript