From: Jamis Buck Date: 2001-05-16T01:33:04+09:00 Subject: [ruby-talk:15176] Handling undefined methods gracefully In Python, there is a pretty graceful way to specify a generic routine to handle requests for attributes/methods that do not exist in an object. Is there a similar feature in Ruby? For example, if I have a simple class: class MySimpleClass def initialize @attrs = Hash.new end def []( name ) @attrs[ name.downcase ] end def []=( name, value ) @attrs[ name.downcase ] = value end end This (admittedly poor) example really just duplicates the functionality of Hash table, but in a case-insensitive manner. Now, the following code works great: test = MySimpleClass.new test[ 'Name' ] = "Jamis" puts test[ 'name' ] But what if I want to treat each new entry in the hash as an actual attribute of the object (though internally continuing to use the hash table to store and query the values), as follows: test = MySimpleClass.new test.name = "Jamis" puts test.name Using 'eval' I'm sure I could come up with something, but all the scenarios I've thought of would be case-sensitive, and I would like to find a way to do it such that 'name', 'Name', 'NAME', 'NaMe', etc. all map to the same attribute, as is the case in the example above that uses the [] method. I hope I'm being clear here. Is there a way to do this in Ruby, without modifying the Ruby source code? (Incidentally, I've already modified my local copy of Ruby to support this, as an exercise... but if there is already support for this, that would naturally be preferable.) Thanks for your help, Jamis -- Jamis Buck minam@rpgplanet.com http://www.rpgplanet.com/dnd3e/generators -----BEGIN GEEK CODE BLOCK----- Version: 3.12 GCS d+(-) s:(-:-) a- C++$ U$ P+ L++$ E- W++$ o>++ K? w++ !O !M PS-(--) !V PE+ Y+ !PGP t+@ 5- X-@ R+>$ tv--@ b++ DI+(++) D--@ G e++ h--- r+++ ------END GEEK CODE BLOCK------