cfpete
cfpete

Reputation: 4443

How to assign ruby's OpenStruct attribute using a variable

How do I assign ruby's OpenStruct attribute using a variable instead of a pre-defined name. I can do the following,

os = OpenStruct.new
os.one = 1
os.two = "Two"

But how do I make it so the attribute name is a variable? For example:

attr_name = "sand_box"
os.#{attr_name} = "Play time!"   #### this doesn't work

Upvotes: 0

Views: 874

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

Alternatively, you could just call the setter method:

os.public_send(:"#{attr_name}=", 'Play time!')

Upvotes: 0

steenslag
steenslag

Reputation: 80065

require 'ostruct'
os = OpenStruct.new
os.one = 1
os.two = "Two"


attr_name = "sand_box"
os[attr_name] = "Play time!"

p os #-> #<OpenStruct one=1, two="Two", sand_box="Play time!">

Upvotes: 1

Related Questions