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
- http://www.linux-mag.com/cache/7432/1.html
- Does Ruby support var references like PHP?
- http://ruby.about.com/od/advancedruby/a/deepcopy.htm