From: "Ara.T.Howard" Date: 2004-06-30T08:02:53+09:00 Subject: Re: [ANN] arrayfields-3.0.0 On Wed, 30 Jun 2004, Ben Giddings wrote: > Is there any reason you didn't just use either constants or variables like: yes. constants: can't be reused - obviously - so tuple_a[NAME] tuple_b[NAME] won't work of NAME is different for both this also doesn't work when the relation is modified. in general there is no guaruntee on the order of fields returned to this is never a good option. variables: i like to do this name, age, ssn = tuple.values_at 'name', 'age', 'ssn' so i already used up those var names - not that i couldn't use 'name_idx', etc. but this starts getting messy fast if you are dealing for four or five tables with 10-20 fields each. lastly there is one nice feature of using the arrayfields method: say you are generating a report from a relation using something like you are suggesting res = pgconn.exec sql tuples, fields = res.tuples, res.fields name, age, ssn = %w(name age ssn).map{|f| fields.index f} YAML::dump( tuples.map do |t| Hash[ 'name' => tuple[name], 'age' => tuple[age], 'ssn' => tuple[ssn], ] end ) and later the relation is modified to now have a new column you'll need to modify the code. whereas if you use the fields this code will work even when the table is modified res = pgconn.exec sql tuples, fields = res.tuples, res.fields YAML::dump( tuples.map do |t| t.fields = fields fields.inject({}){|h,f| h[f] = t[f]; h} end ) of course you could write the code to have this feature either way - my point is just that when you extract the indexes into named vars you limit the way your code will work as the database add/drops fields... i was originally also doing alot of this sort of thing: def where_clause tuple, op = ' or ' clauses = tuple.fields.map do |field| "#{ field } = '#{ tuple[field] }'" end clauses.join op end which just started to get painful when the tuple didn't know it's own field names... you can imagine doing alot of this stuff if you have to map fields to var names and pass this mapping into each sql generation method... cheers. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | A flower falls, even though we love it; | and a weed grows, even though we do not love it. | --Dogen ===============================================================================