lib/methodic_hash.rb in eymiha_util-0.1.2 vs lib/methodic_hash.rb in eymiha_util-0.1.3

- old
+ new

@@ -1,30 +1,33 @@ -# The MethodicHash is some method_missing magic that tries to lookup values -# when keys are passed in as method calls. For instance, if +# The MethodicHash is some method_missing magic that uses method names as hash +# keys, so hash assignment and lookup appear to be attribute writing and +# reading. For instance, if # # mh = MethodicHash.new -# mh['four'] = 'iv' -# mh[:seven] = 'vii' +# mh['four'] = 'iv' +# mh[:seven] = 'vii' +# mh.eighteen = 'xviii' # # then # -# mh['four'] ---> 'iv' -# mh[:four] ---> 'iv' -# mh.four ---> 'iv' +# mh['four'] ---> 'iv' +# mh[:four] ---> 'iv' +# mh.four ---> 'iv' +# mh['seven'] ---> 'vii' +# mh[:seven] ---> 'vii' +# mh.seven ---> 'vii' +# mh['eighteen'] ---> 'xviii' +# mh[:eighteen] ---> 'xviii' +# mh.eighteen ---> 'xviii' # -# and -# -# mh['seven'] ---> 'vii' -# mh[:seven] ---> 'vii' -# mh.seven ---> 'vii' -# # This allows access to simply declared facts to be embedded in Ruby code and # leverages the possibility of hashing procs. # # Note that if the hash uses anything but strings or symbols as keys, the # magic stands a good chance of failing, raising an error or acting in a -# bizarre manner. +# bizarre manner. Note also that methods of the Hash cannot be used as +# 'attribute' names. class MethodicHash < Hash # Try to look up using a key directly, or if that fails as a string, or as # a symbol as last resort. If a symbol conversion doesn't exists, rescue # with a nil. @@ -34,11 +37,17 @@ rescue nil end end - # A missing method is assummed to be the value of a key. + # A missing method is assummed to be the assignment of a value of a key, or + # the lookup of a value with a key. def method_missing(method,*args) - self[method] + string = method.to_s + if string[string.length-1,1] == '=' + self[string[0,string.length-1].to_sym] = args[0] + else + self[method] + end end end