Generating instance variable for a class

D

donn

What I am trying to do is use a hash to tie attributes to an input
record layout from which the attribute will be created and their
values are set. What I am thinking is that the hash can provide the
record layout to class users and it can provide loop control for
nearly everything associated with it. I would like to create an
attribute for each hash key. It would be great if I could use "attr"
to create the instance and and associated access method. The
following does function, but it looks like a kludge. Is there a
better way of doing it?

class MDhdr < MD_Record # Header record
attr_reader :infmt
def initialize(rec)
@infmt = {
:JobId => [0,7],
:Version => [8,11],
:HistorySeq => [12,15],
:HistorStatus => [16,16],
:HistoryId => [17,24],
:UserJobId => [25,49],
:JobName => [50,79]
}.each {|key,arg| eval "@#{key} = rec[#{arg[0]}..#{arg[1]}]" }
puts @JobId

end
end

The ultimate goals here are lazy, accuracy, and no reduncancy. I can
update the hash with new record layout positions and a instance name,
and I'm done with updating the class. The alternative is to have an
attr_accessor for all the variables, a listing of all the variables,
and each variable assigned.

Thanks for your recommendations.
 
G

Gregory Brown

What I am trying to do is use a hash to tie attributes to an input
record layout from which the attribute will be created and their
values are set.

ri instance_variable_set

-greg

P.S.
fwiw: ruby style is @like_this, not @LikeThis
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top