Allen wrote:
> Hi!
>
> [...]
> Following is my class for your inspection. I can kludge something that
> works, but I want to learn the *best* method. Thanks!
>
> ########################
> class QlbRecord
>    @@cols = [ :address, :classes, :status, :dpend, :cremote ]
>    @@cols.each { |a| attr a,true }
>
>    def initialize(record_string=nil)
>      from_s(record_string) if record_string
>    end
>
>    def from_s(record_string)
>      arec = record_string.split(/\t/)
>      @@cols.each { |c| self.c = arec.shift }
> ##---------------------> I want it to go to @address, @classes, etc
>    end
>
>    def to_s
>      str=''
>      @@cols.each { |c| str += (str>'' ? "\t" : '') + self.c }
> ##--------------------------------------------> from @address, etc.
>      str
>    end
> end
>
>

If you're going dynamic, the need for attribute accessors is reduced.
Here, instance_variable_get and ..._set are used:


class QlbRecord
   @@cols = [ :@address, :@classes, :@status, :@dpend, :@cremote ]

   def initialize(record_string=nil)
     from_s(record_string) if record_string
   end

   def from_s(record_string)
     record_string.split(/\t/).each_with_index do |c, ix|
       instance_variable_set(@@cols[ix], c)
     end
   end

   def to_s
     @@cols.map do |col|
       instance_variable_get(col)
     end.join("\t")
   end
end

qr1 = QlbRecord.new("1 addr aaa\tclasses aa\tst1\tdp1\tcr1")
p qr1
  #-> #<QlbRecord:0x2c8b9e8 @address="1 addr aaa", @dpend="dp1",
  #->    @status="st1", @classes="classes aa", @cremote="cr1">
p qr1.to_s
  #-> "1 addr aaa\tclasses aa\tst1\tdp1\tcr1"



> Also, I don't completely understand how symbols work or
> why they are needed.


If you use strings to identify fields, each time you write the
field name, a new string is created.  Symbols are unique and
memory-efficient.

p 'cremote'.object_id  #-> 23356052
p 'cremote'.object_id  #-> 23356016
p 'cremote'.object_id  #-> 23355992
puts
p :@cremote.object_id  #-> 3504654
p :@cremote.object_id  #-> 3504654
p :@cremote.object_id  #-> 3504654


Hope that's of use.

daz