Hi!
Ruby n00b here, but experienced in Perl and Python and many others,
looking for guidance in my first program.
I want to build a class mirroring a flat file record that uses column
names as accessor methods, I want to dynamically assign an attribute
from a parsed string and assign it from the postitional list of symbols.
rec = QlbRecord.new(file_line)
rec.dpend += 5
puts rec.address
First, I Set up the class attributes in the class.
@@cols = [ :address, :classes, :status, :dpend, :cremote ]
@@cols.each { |a| attr a,true }
Next, I would populate the fields as such....
arec = record_string.split(/\t/)
@@cols.each { |c| self.c = arec.shift }
where c is the sumbol of the attribute to set. This is wrong.
Am I going in the right direction? It is like using a hash
data[c] = arec.shift
though I want to access the columns through methods (rec.address, etc.)
Is there a class in the library I should be using instead? Or do I
really just need to replicate code (ick!) for each data field?
address = arec.shift
classes = arec.shift
... etc. ...
Also, I don't completely understand how symbols work or why they are
needed.
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