Read OpenStruct attribute name from variable

O

Oliver Cromm

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*"?
 
A

Ara.T.Howard

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*"?

key = 'foo'

value = open_struct.send 'foo'

open_struct.send "#{ foo }=", value

hth.

-a
--
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| My religion is very simple. My religion is kindness.
| --Tenzin Gyatso
===============================================================================
 
O

Oliver Cromm

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
 

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

Forum statistics

Threads
474,173
Messages
2,570,937
Members
47,481
Latest member
ElviraDoug

Latest Threads

Top