Is there a library/mechanism for an object/hash hybrid?

D

dtrusty

Hi,

There are times when I want to store items in a hash, and yet refer
the items
using class/object method syntax.

For example, I may want to do this:
myhash['aaa'] = 'bbb'
and then be able to refer to the 'aaa' element either as
myhash['aaa']
--or--
myhash.aaa

I started writing my own class to do this, but I wanted to check to
see if anyone had
already done so.

What do you think?

Thanks,

David
 
T

Trans

Facet's OpenObject

gem install facets

require 'facet/openobject'

oo = OpenObject.new

oo.a = 1

oo[:a] #=> 1

T.
 
J

Jan Friedrich

Gary said:
OpenStruct doesn't define access via the indexing method:

info = OpenStruct.new

info.name = 'Gary'
info[:name] # undefined method
It's Ruby, define it. :)
class OpenStruct
def [] arg
self.send arg
end


regards,
Jan
 
G

Gary Wright

Gary said:
OpenStruct doesn't define access via the indexing method:

info = OpenStruct.new

info.name = 'Gary'
info[:name] # undefined method
It's Ruby, define it. :)

Of course. I was just pointing out that OpenStruct didn't
actually provide the features that the OP had asked for.

You can always roll your own.


Gary Wright
 
R

Rick DeNatale

Hi,

There are times when I want to store items in a hash, and yet refer
the items
using class/object method syntax.

For example, I may want to do this:
myhash['aaa'] = 'bbb'
and then be able to refer to the 'aaa' element either as
myhash['aaa']
--or--
myhash.aaa

I started writing my own class to do this, but I wanted to check to
see if anyone had
already done so.

I just read about this in a blog yesterday:
http://www.oreillynet.com/ruby/blog/2007/03/camping_hashwithreallyindiffer.html

The camping framework has a HashWithIndifferentAccess which does this.

Not to be confused with the class HashWithIndifferentAccess in Rails
(actually in ActiveSupport)

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

IPMS/USA Region 12 Coordinator
http://ipmsr12.denhaven2.com/

Visit the Project Mercury Wiki Site
http://www.mercuryspacecraft.com/
 

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
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top