Strange problem with ruby-dbi and arrays

No clue what I am doing wrong here. It’s hard to give a complete test
case because it involves a database but maybe someone can spot what
I’m doing wrong. with each fetch, tlist is growing by one, but all
the elements in tlist get set to the last value of row. I put sample
output from the script at the end.

require ‘dbi’
conn = DBI.connect(blah blah)

tlist = []
sth = conn.prepare(“SELECT sequence_number from vital_transact where
merchant_id = ?”)
sth.execute(‘poi2’)
while row = sth.fetch do
tlist << row
p “tlist=#{tlist.length} row=#{row.length}”
p tlist
p row
end
sth.finish
p “”
p tlist

“tlist=1 row=1”
[“0012”]
[[“0012”]]
“tlist=2 row=1”
[“0013”]
[[“0013”], [“0013”]]
“tlist=3 row=1”
[“0014”]
[[“0014”], [“0014”], [“0014”]]
“tlist=4 row=1”
[“0015”]
[[“0015”], [“0015”], [“0015”], [“0015”]]
“tlist=5 row=1”
[“0019”]
[[“0019”], [“0019”], [“0019”], [“0019”], [“0019”]]
“tlist=6 row=1”
[“0021”]
[[“0021”], [“0021”], [“0021”], [“0021”], [“0021”], [“0021”]]
“tlist=7 row=1”
[“0022”]
[[“0022”], [“0022”], [“0022”], [“0022”], [“0022”], [“0022”], [“0022”]]
“tlist=8 row=1”
[“0023”]
[[“0023”], [“0023”], [“0023”], [“0023”], [“0023”], [“0023”], [“0023”],
[“0023”]]
“tlist=9 row=1”
[“0024”]
[[“0024”], [“0024”], [“0024”], [“0024”], [“0024”], [“0024”], [“0024”],
[“0024”], [“0024”]]
“”
[[“0024”], [“0024”], [“0024”], [“0024”], [“0024”], [“0024”], [“0024”],
[“0024”], [“0024”]]

Hmm, if I change:
tlist << row

to
tlist.concat(row)

Then it works. Why is that?

Never mind, that doesn’t work it flattens row before appending it.

Ok I get it now. Each element I append onto tlist still references
row, so each time through the loop, all the row elements in tlist get
set to the current value of row. The following works.

r = row.to_a.clone
tlist << r

On Aug 16, 2006, at 1:12 AM, snacktime wrote:

Hmm, if I change:
tlist << row

to
tlist.concat(row)

Then it works. Why is that?

Guessing but perhaps fetch reuses the same object to store the query
result.
What if you do

while row = sth.fetch.dup do

end

Sort of works. On the last loop it throws this:

`dup’: can’t dup NilClass (TypeError)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs