How to use a hash inside a Struct?

J

Jayson Williams

Is there a way to use a hash inside a Structure. Something like:

object = Struct.new(Hash.new(), :attr2, :attr3)

I know this doesn't work, but do you get the idea of what I am trying to do?

Jayson
 
T

Thomas Adam

Is there a way to use a hash inside a Structure. Something like:

object = Struct.new(Hash.new(), :attr2, :attr3)

Struct objects except Symbols. What is it you're trying to do?

-- Thomas Adam
 
J

Jayson Williams

I am creating a class that creates elements of a house. For the part
that creates new rooms, I wanted to link the room name with a room id.
There may be multiple rooms with the same name, but only one room with
the unique combination of name and id. I was thinking to use a Hash
inside the structure definition of the room for the name and id.
 
J

Jayson Williams

I think both of these methods will work

Thing = Struct.new:)attr1,:attr2,:attr3)
t = Thing.new(Hash.new, nil, nil)

and...
require 'ostruct'

house = OpenStruct.new
house.room = {:room_id => 'id', :room_name => 'name'}
house.attr1 = 'some value'

I was thinking that the attributes in the structure had to be typed
first (a bit of c left in me). But it makes sense that I can set up
the attribute and put whatever I want there.
The second method looks a bit RubyTk'ish. I wonder if RubyTk uses OpenStruct.
Anyway, Thanks. This is just what I was looking for

Jayson
 

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,999
Messages
2,570,246
Members
46,839
Latest member
MartinaBur

Latest Threads

Top