Chad Perrin wrote in post #1012264:
> Is there a way to use attr_accessor, or something like it (without
> writing it from scratch), for hash keys?  For instance:
>
>     class Foo
>       attr_accessor :bar[:one], :bar[:two]
>       def initialize(bar)
>         @bar = bar
>       end
>     end
>
> Obviously, :bar[:one] and :bar[:two] won't work, because symbols don't
> have [] methods, but that should illustrate the general gist of what I'm
> asking (I hope).  I'd just like to avoid the clutter of writing a bunch
> of basic accessors myself, the long way, in a class definition where I'd
> like to keep all the data in a hash but have direct accessor method ways
> to work with specific key=>value pairs.

irb(main):001:0> Foo = Struct.new :one, :two
=> Foo
irb(main):002:0> f = Foo.new
=> #<struct Foo one=nil, two=nil>
irb(main):003:0> f[:one]
=> nil
irb(main):004:0> f[:one] = 1
=> 1
irb(main):005:0> f.one
=> 1
irb(main):006:0> f.one = 111
=> 111
irb(main):007:0> f[:one]
=> 111
irb(main):008:0> Hash[*f.members.zip(f.to_a).flatten]
=> {:one=>111, :two=>nil}
irb(main):009:0> class Struct
irb(main):010:1> def to_hash;Hash[*members.zip(to_a).flatten];end
irb(main):011:1> end
=> nil
irb(main):012:0> f.to_hash
=> {:one=>111, :two=>nil}

Kind regards

robert

-- 
Posted via http://www.ruby-forum.com/.