Looks like an OpenStruct bug / restriction in section 1.8.7, where there is no BlankSlate object called by the implementation, which it uses method_missingto decide whether this is a special property or not.
Here, a custom class, similar to OpenStruct, does what you ask for in section 1.8.7; Feel free to expand it and make it more multifunctional.
class MemoStruct
def initialize( h=nil )
h.each{ |k,v| add_field(k,v) } if h
end
def add_field( name, value=nil )
inst = :"@#{name}"
(class << self; self; end).class_eval do
define_method(name){ instance_variable_get inst }
define_method("#{name}="){ |v| instance_variable_set inst,v }
end
instance_variable_set(inst,value)
end
def []=( name, value )
add_field(name,value)
end
end
hash = MemoStruct.new :id=>123, :name=>"Jim"
p hash.id
hash["new_field"] = "stuff"
p hash.new_field
source
share