From: "Ara.T.Howard" Date: 2005-11-02T11:52:08+09:00 Subject: Re: How can I avoid this boring code? On Wed, 2 Nov 2005, Sam Kong wrote: > Hi! > > I'm creating a class. > I wonder if there's a better way. > > require 'dbi' > > class Person > attr_accessor :person_id, > :last_name, > :first_name, > :home_phone, > :work_phone, > :address, > :city, > :state, > :zip > > def initialize(row=nil) > if row.class == DBI::Row then > @person_id = row.by_field("person_id") > @last_name = row.by_field("last_name") > @first_name = row.by_field("first_name") > @home_phone = row.by_field("home_phone") > @work_phone = row.by_field("work_phone") > @address = row.by_field("address") > @city = row.by_field("city") > @state = row.by_field("state") > @zip = row.by_field("zip") > end > end > end > > The code in initialize method is very boring. > How could I make it simpler? class Person FIELDS = %w( person_id last_name first_name home_phone work_phone address city state zip ) def initialize r = nil FIELDS.each{|f| send "#{ f }=", r.by_field(f)} if row.class == DBI::Row end end if the Person class can dynamically set FIELDS by inspecting a table - so much the better. hth. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | anything that contradicts experience and logic should be abandoned. | -- h.h. the 14th dalai lama ===============================================================================