Re: ruby/postgres - getting assoc array of rows?

From: CSN <cool_screen_name90001(at)yahoo(dot)com>
To: Michael Fuhr <mike(at)fuhr(dot)org>
Cc: pgsql-interfaces(at)postgresql(dot)org
Subject: Re: ruby/postgres - getting assoc array of rows?
Date: 2005-11-20 10:31:45
Message-ID: 20051120103145.96545.qmail@web52901.mail.yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-interfaces


I tried:
puts "by name: #{row['id']} #{row['name']}"

but it exits with:
pg.rb:16:in `[]': can't convert String into Integer (TypeError)

The by position line does work though.

thanks
csn

--- Michael Fuhr <mike(at)fuhr(dot)org> wrote:

> On Sat, Nov 19, 2005 at 08:14:40PM -0800, CSN wrote:
> > Looking at the docs here:
> > http://ruby.scripting.ca/postgres/reference.html
> >
> > there doesn't appear to be an easy way to get an associative row
> > of rows returns.
>
> What exactly are you looking for? The example you posted returns
> an array of hashes, but depending on what you're doing all that
> work might not be necessary. PGconn#exec returns a PGresult object,
> the PGresult#each iterator yields PGrow objects, and PGrow#[] accepts
> both numeric and text indexes. Example:
>
> % psql -d test -c 'SELECT id, name FROM people'
> id | name
> ----+-------
> 1 | Alice
> (1 row)
>
> % cat test.rb
> require 'postgres'
> conn = PGconn.new('dbname=test')
> res = conn.exec('SELECT id, name FROM people')
> res.each do |row|
> puts "by name: #{row['id']} #{row['name']}"
> puts "by position: #{row[0]} #{row[1]}"
> end
> res.clear
> conn.close
>
> % ruby test.rb
> by name: 1 Alice
> by position: 1 Alice
>
> You could also convert the PGresult object into an array of PGrow
> objects with a one-liner, although you wouldn't get automatic bytea
> handling as in the function you posted:
>
> rows = res.collect
>
> Will any of this work for you? If not then please provide more
> detail.
>
> --
> Michael Fuhr
>



__________________________________
Yahoo! Mail - PC Magazine Editors' Choice 2005
http://mail.yahoo.com

In response to

Responses

Browse pgsql-interfaces by date

  From Date Subject
Next Message Michael Fuhr 2005-11-20 15:56:14 Re: ruby/postgres - getting assoc array of rows?
Previous Message Michael Fuhr 2005-11-20 05:52:27 Re: ruby/postgres - getting assoc array of rows?