[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: Asking for style critics: Collecting the result of a query

Ball, Donald A Jr (Library)

6/5/2007 3:21:00 PM

> Problem: Fetch result of a query (it happens to be a SQL
> query to a database, but the essential point here is that I
> need to generate the resulting lines piecewise, each
> iteration returning the next row as an array of values). The
> result should be returned as a matrix (i.e. array of arrays).
> In practice, the number of rows returned will be well below
> 1000, each row containing around 10 items.
>
> Here is my code:
>
> def fetch_result(querystring)
> result=[]
> qres = dbhandle.query(qstr)
> while row = fetch_result.fetch_row # deliver next row
> result.push row # add row to the result array - is this OK?
> end
> result # return result array
> end
>
> I suspect there might be an overhead in appending to an array
> new rows piecewise as I'm doing it here. Is there a better
> way to do it?

If the consumer of these data is just going to iterate over the
resulting array and do stuff with the rows, you might as well just yield
the results and cut out the middleman. It might look something like:

def each_result(query)
results = dbh.query(query)
while row = results.fetch_row
yield row
end
end

each_result {|row| puts row.inspect}

Of course, if you need an array for any reason, what you're doing
looking fine to me, although doing:

result << row

is more idiomatic ruby, I believe.

- donald