Multiple initialization of auto-vivifying hashes u

2019-03-02 18:16发布

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

  1. http://www.linux-mag.com/cache/7432/1.html
  2. Does Ruby support var references like PHP?
  3. http://ruby.about.com/od/advancedruby/a/deepcopy.htm

1条回答
劳资没心,怎么记你
2楼-- · 2019-03-02 18:57

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

查看更多
登录 后发表回答