--bcaec51d21a68443ea04a8a74b12 Content-Type: text/plain; charset=ISO-8859-1 On Thu, Jul 21, 2011 at 4:17 PM, Chad Perrin <code / apotheon.net> wrote: > 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 ar > 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 alue pairs. > > -- > Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ] > You could coerce forwardable into kind of behaving like this: require 'forwardable' class Foo extend Forwardable def_delegator '@bar', '[], :one', 'one' def_delegator '@bar', '[], :two', 'two' def initialize(bar) @bar ar end end foo oo.new one: 1, two: 2 foo.one # 1 foo.two # 2 But if they ever change its implementation, this will break >.< Honestly, I'd probably do what Sean did. --bcaec51d21a68443ea04a8a74b12--