# Generating instance variable for a class

**URL:** <https://www.ruby-forum.com/t/generating-instance-variable-for-a-class/85184>\
**Category:** Ruby\
**Created:** [February 11, 2007, 12:56am UTC](https://www.ruby-forum.com/t/generating-instance-variable-for-a-class/85184 "2007-02-11T00:56:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [February 11, 2007, 12:56am UTC](https://www.ruby-forum.com/t/generating-instance-variable-for-a-class/85184/1 "2007-02-11T00:56:12Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [February 11, 2007, 1:02am UTC](https://www.ruby-forum.com/t/generating-instance-variable-for-a-class/85184/2 "2007-02-11T01:02:12Z")

</div>

On 2/10/07, removed\_email\_address@domain.invalid [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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
