Multiple initialization of auto-vivifying hashes using a new operator in Ruby

我是研究僧i 提交于 2019-12-02 11:21:02

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!