From: "A. S. Bradbury" Date: 2006-08-08T20:54:34+09:00 Subject: Re: method_missing to define_method On Monday 07 August 2006 04:07, Matt Todd wrote: > Given the circumstance that you don't want to explicitly predefine > your methods for properties, etc, but that you're certain your > parameters won't somehow change to affect your design, would it be > beneficial to have method_missing define the method so that > method_missing doesn't have to be called in case the property special > method is called again? > > For instance... > > class Person > @attributes = {} > def initialize attributes > @attributes.merge! attributes > end > def method_missing name > if @attributes.has_key? name > class_eval do > define_method(name) do |name| > @attributes[name] > end > end > else > # other magic > end > end > end > > So, if I do... > > p = Person.new { :name => "Papa", :age => 66, :phone => "404-932-3955" } > > the first time I ask for... > > p.age > > the method :age is created. And the next time I call it, then it just > executes the method I juist created. Have you seen OpenStruct in the standard library? require 'ostruct' p = OpenStruct.new({ :name => "Papa", :age => 66, :phone => "404-932-3955" }) You can add new fields after object creation, p.occupation="Doctor". I'm also curious as to whether there's any advantage to defining methods (as OpenStruct does) vs just looking up hash keys in method_missing. Alex