[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Read OpenStruct attribute name from variable

Oliver Cromm

6/3/2005 7:01:00 PM

Can't find that discussed anywhere, but maybe I just don't know how to
look.

I have lots of style parameters in an object. First, I implemented it as
a hash, so I have the method

def set_style(stylepars)
stylepars.each {|key, val| @style[key] = val}
end

Now I want to exchange the Hash for an OpenStruct, because it's much
easier on the eyes in statements like this:

sepline = @style['verticalsep'] + sepline +
@style['horizontalsep']*@style['padding'] +
@style['verticalsep'] if @style['box']

But how can I set "the attribute whose name is in the variable *key*"?
--
Oliver C.
45n31, 73w34
Temperatur: 26.8°C (3 June 2005 2:00 PM EDT)
2 Answers

Ara.T.Howard

6/3/2005 9:54:00 PM

0

Oliver Cromm

6/6/2005 4:18:00 PM

0

* Ara.T.Howard@noaa.gov wrote:

> On Fri, 3 Jun 2005, Oliver Cromm wrote:
>
>> But how can I set "the attribute whose name is in the variable *key*"?
>
> key = 'foo'
>
> value = open_struct.send 'foo'
>
> open_struct.send "#{ foo }=", value
>
> hth.

A mathematics professor once told me that textbooks should contain
enough errors, so that students would have to spot them, and not get
lazy.
So, yes, after changing the obvious error, the above works fine, thanks.

open_struct.send "#{ key }=", value
--
A computer will do what you tell it to do, but that may be much
different from what you had in mind. - Joseph Weizenbaum