我如何在 Ruby 中的 PG::Result 上弹出?

How would I do a pop on a PG::Result in Ruby?

运行 我得到的 pgsql 数据库结果集上的弹出:

undefined method `pop' for #<PG::Result:0x0000000273dc08>

我想获取该结果集的前 5 个,对它做一些处理,然后对接下来的 5 个再做一次。我不想 运行 我的查询两次,因为它相当长查询。

我如何在 ruby 中执行此操作?

我是 运行宁 ruby 2.1 和 rails 3.0.

问题是PGResult不是一个数组,它是一个对象。您需要使用 to_a 方法将其转换为数组。

PG::ResultEnumerable 所以你可以在上面使用 each_slice:

your_pg_result.each_slice(5) do |array|
  # array is at most five rows from the result set
  # on each iteration so do whatever needs to be done
end

如果您需要区分迭代,则将 with_index 放入组合中:

your_pg_result.each_slice(5).with_index do |array, i|
  # ...
end