Pushing to an array not working as expected
        Posted  
        
            by 
                Ross Attrill
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Ross Attrill
        
        
        
        Published on 2012-11-18T04:51:38Z
        Indexed on 
            2012/11/18
            5:00 UTC
        
        
        Read the original article
        Hit count: 156
        
ruby
When I execute the code below, my array 'tasks' ends up with the same last row from the dbi call repeated for each row in the database.
require 'dbi'
require 'PP'
dbh = DBI.connect('DBI:ODBC:Driver={SQL Server Native Client 10.0};Server=localhost,1433;Database=db;Uid=db;Pwd=mypass', 'db', 'mypass')
sth = dbh.prepare('select * from TASK')
sth.execute
tasks = Array.new
while row=sth.fetch do
    p row
    tasks.push(row)
end
pp(tasks)
sth.finish
So if I have two rows in my TASK table, then instead of getting this in the tasks array:
[[1, "Task 1"], [2, "Task 2"]]
I get this
[[2, "Task 2"], [2, "Task 2"]]
What am I doing wrong?
© Stack Overflow or respective owner