What is the easiest way to create an object on the fly with accessor methods defined by a hash? For example, if I have a hash:

{foo: "Foo", bar: "Bar"}

I want to have an object that has accessor methods foo, foo=, bar, and bar= with the initial value "Foo", and "Bar", respectively. I can think of doing:

module ObjectWithAccessor
  def self.new h; Struct.new(*h.keys).new(*h.values) end
end

o = ObjectWithAccessor.new(foo: "Foo", bar: "Bar")
o.foo # => "Foo"

but, I don't need to have multiple instances of them with the same particular set of keys, but rather want to create new instances of it each time with possibly different set of keys, so creating a new class with Struct each time for each object seems overkill, and I want to avoid that. Is there a better way to do this?

Edit
Report