[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

strange problem with ruby-dbi and arrays

snacktime

8/16/2006 4:58:00 AM

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"]]

5 Answers

snacktime

8/16/2006 5:12:00 AM

0

Hmm, if I change:
tlist << row

to
tlist.concat(row)

Then it works. Why is that?

snacktime

8/16/2006 5:16:00 AM

0

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

On 8/15/06, snacktime <snacktime@gmail.com> wrote:
> Hmm, if I change:
> tlist << row
>
> to
> tlist.concat(row)
>
> Then it works. Why is that?
>

Logan Capaldo

8/16/2006 5:20:00 AM

0


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


snacktime

8/16/2006 5:28:00 AM

0

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

snacktime

8/16/2006 5:28:00 AM

0

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

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

>
> Guessing but perhaps fetch reuses the same object to store the query
> result.
> What if you do
>
> while row = sth.fetch.dup do
> ...
> end
>
>
>