From: Brian Candler Date: 2011-02-04T17:56:01+09:00 Subject: Re: Setter method for Hash value Rolf Pedersen wrote in post #979464: > Hi Brian (and others who have contributed with suggestions along the > same > line) > > It's not the class MyClass that I'd like to behave like a Hash. > I'm trying to make getter and setter methods for a virtual hash property > called props. Then the 'props' object which you return needs methods [] and []= defined, which do whatever you want them to do. I see you are using these methods on the class itself (not instances of the class): SomeClass::set_prop(key, value) In that case, you can define them as class methods: class SomeClass def self.[](key) get_prop(key) end def self.[]=(key,value) set_prop(key,value) end end And then simply return the class itself: class MyClass def props SomeClass end end If you were using *instances* of SomeClass, then personally I would just define methods [] and []= as instance methods. Depending on how Hash-like you want this object to be, you may want to define some other methods too. If there is some particular reason why you can't do that, then you would have to return a proxy object, whose [] and []= methods are relayed to get_prop and set_prop on the underlying SomeClass object. If you still want props to return an actual Hash, then it will have to be a Hash which has been modified so that []= performs the operation on the underlying object. You can use delegate.rb, or you can explicitly delegate those methods which you want to. Here is some code from CouchTiny which wraps a Hash: module CouchTiny # A class which delegates a small subset of methods to a Hash (to keep # the space as clear as possible for accessor names) class DelegateDoc attr_accessor :doc def initialize(doc = {}) @doc = doc.to_hash end def to_hash @doc end def ==(other) @doc == other # .to_hash is done by Hash#== end def to_json(*args) @doc.to_json(*args) end alias :orig_respond_to? :respond_to? def respond_to?(*m) orig_respond_to?(*m) || @doc.respond_to?(*m) end def [](k) @doc[k.to_s] end def []=(k,v) @doc[k.to_s] = v end def key?(k) @doc.key?(k) end def has_key?(k) @doc.has_key?(k) end def delete(k) @doc.delete(k) end def merge!(h) @doc.merge!(h) end def update(h) @doc.update(h) end def dup self.class.new(@doc.dup) end #def method_missing(m, *args, &block) # @doc.__send__(m, *args, &block) #end end end Regards, Brian. -- Posted via http://www.ruby-forum.com/.