0

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Julien Lamarche
  • 931
  • 1
  • 12
  • 29

2 Answers2

2

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.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • And hope that the result set fits into memory. It'd be better/safer/more scalable to iterate over it or retrieve the data in chunks. – the Tin Man Jun 19 '15 at 23:03
1

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
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Though @user4703663 answer was closer to the question, this answer is a closer fix to the problem I was attempting to solve. Thanks to both of you for your contributions. – Julien Lamarche Jun 19 '15 at 22:02