I would like to initialize several auto-vivifying hashes by one-line expression. So far I came to an extra method for the AutoHash object:
class AutoHash < Hash
...
def few(n=0)
Array.new(n) { AutoHash.new }
end
which allows me to do the following
a, b, c = AutoHash.new.few 3
However, I feel that one can make the following sentence possible by defining a new operator :=
a := b := c = AutoHash.new
Could you help me to implement this?
Do I have to use superators?
require 'superators'
class AutoHash < Hash
...
superator ":=" do |operand|
if operand.kind_of? Hash
...
else
...
end
end
Update: Now I see that the operator needs to be defined outside the class. Is it possible to define such object clone operator?
Update2 More clear definition of method few, thanks to Joshua
References
Where you ask for
a := b := c := AutoHash.new.few 3I think (not sure I understand your desire) that you really wanta,b,c=Autohash.new.few 3Why does few take variable args, when you only ever use the first?
I also find your creation of the return value to be confusing, maybe try
Beyond that, it seems like
fewshould be a class method.a,b,c=AutoHash.few 3which will work if you defined few on the class:If
a,b,c=AutoHash.few 3isn’t what you’re looking for, and you really want to implement your own operator, then check out Hacking parse.y, which was a talk given at RubyConf 2009. You can watch the presentation at http://rubyconf2009.confreaks.com/19-nov-2009-17-15-hacking-parsey-tatsuhiro-ujihisa.html and you can see the slides at http://www.slideshare.net/ujihisa/hacking-parsey-rubyconf-2009