问题
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
回答1:
Where you ask for a := b := c := AutoHash.new.few 3
I think (not sure I understand your desire) that you really want a,b,c=Autohash.new.few 3
Why 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
def few(n=0)
Array.new(n) { AutoHash.new }
end
Beyond that, it seems like few
should be a class method. a,b,c=AutoHash.few 3
which will work if you defined few on the class:
def AutoHash.few(n=0)
Array.new(n) { AutoHash.new }
end
If a,b,c=AutoHash.few 3
isn'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
来源:https://stackoverflow.com/questions/3165331/multiple-initialization-of-auto-vivifying-hashes-using-a-new-operator-in-ruby