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

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

[email protected] schrieb:

Hi,

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

What do you think?
http://ruby-doc.org/stdlib/libdoc/ostruct/rdoc/classes/OpenStruct.html

regards
Jan

On Mar 30, 2007, at 2:45 PM, Jan F. wrote:

[email protected] schrieb:

Hi,

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

What do you think?
http://ruby-doc.org/stdlib/libdoc/ostruct/rdoc/classes/OpenStruct.html

OpenStruct doesn’t define access via the indexing method:

info = OpenStruct.new

info.name = ‘Gary’
info[:name] # undefined method

Gary W.

Gary W. schrieb:

OpenStruct doesn’t define access via the indexing method:

info = OpenStruct.new

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

regards,
Jan

Gary W. wrote:

OpenStruct doesn’t define access via the indexing method:

info = OpenStruct.new

info.name = ‘Gary’
info[:name] # undefined method

Hal F. wrote a class called “SuperStruct”. Maybe it’s what you’re
looking for: http://sstruct.rubyforge.org/.

Facet’s OpenObject

gem install facets

require ‘facet/openobject’

oo = OpenObject.new

oo.a = 1

oo[:a] #=> 1

T.

On Mar 30, 2007, at 4:15 PM, Jan F. wrote:

Gary W. schrieb:

OpenStruct doesn’t define access via the indexing method:

info = OpenStruct.new

info.name = ‘Gary’
info[:name] # undefined method
It’s Ruby, define it. :slight_smile:

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 W.

On 3/30/07, [email protected] [email protected] wrote:

–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:

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/