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

524 views Asked by At

Running a pop on a result set from a pgsql database I get:

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

I want to get the first 5 of that result set, do something with it, then do it again with the next 5. I don't want to run my query twice as it is a fairly long query.

How would I do this in ruby?

I am running ruby 2.1 and rails 3.0.

2

There are 2 answers

1
mu is too short On BEST ANSWER

PG::Result is Enumerable so you could just use each_slice on it:

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

If you need to differentiate the iterations then throw a with_index into the mix:

your_pg_result.each_slice(5).with_index do |array, i|
  # ...
end
1
Richard Hamilton On

The problem is that PGResult is not an array, it is an object. You need to convert it to an array with the to_a method.