From: Mathieu Bouchard Date: 2001-10-24T20:49:17+09:00 Subject: [ruby-talk:23181] Re: obj.__dict__ On Wed, 24 Oct 2001, Rich Kilmer wrote: > So...in Python you can use this: > obj.__dict__['attrName']=value > ...to get direct access to (get/set) the values of every attribute on > an object. > > In Ruby every object attribute is private and can only be accessed > through a method...period. Exposing the __dict__ "bag" on an object > exposes the entire state of that object for public consumption. Which reminds me that I wrote a Ruby emulation of obj.__dict__ 5 months ago. I finally checked-in this nice sample of M�taRuby usage this morning. (this is one-third of samples/ReflectionHashes.rb). ----------------8<----------------cut-here----------------8<---------------- class InstanceVariablesHash; include HollowHash, SimpleHashP # victim is any object. # it only works on Ruby-visible instance-variables, # i.e. those accessible by "@" names. def initialize(victim) @victim = victim end def length @victim.instance_variables.length end def canonize_name(k) if Symbol===k; k=k.to_s; end String===k && k =~ /^(@[A-Za-z_]\w*)$/ or raise "Invalid Name" k end def has_key?(k) k = canonize_name k !! @victim.instance_variables.index(k) end def get(k) k = canonize_name k @victim.instance_eval k end def put(k,v) k = canonize_name k @victim.instance_eval "#{k} = ObjectSpace._id2ref(#{v.id})" end def remove(k) # the best I can do put(k,nil) end def each_key(&proc) @victim.instance_variables.each(&proc) end end ----------------8<--------------d�coupez-ici--------------8<---------------- > methods. The same is NOT true for Python. It provides "privacy" > through obfuscation (name mangling) but its still easy to get around > (because everything is still held in the __dict__). Well, this may be interesting from a $SAFE perspective. If you are not coming this way from a $SAFE perspective, chances are that I don't give a... ________________________________________________________________ Mathieu Bouchard http://hostname.2y.net/~matju