1

我想通过一行表达式初始化几个自动激活的哈希。到目前为止,我为该AutoHash对象找到了一个额外的方法:

class AutoHash < Hash
  ...
  def few(n=0)
    Array.new(n) { AutoHash.new }
  end

这使我可以执行以下操作

a, b, c = AutoHash.new.few 3

但是,我觉得可以通过定义一个新的运算符来使下面的句子成为可能:=

a := b := c = AutoHash.new

你能帮我实现这个吗?


我必须使用superators吗?

require 'superators'

class AutoHash < Hash
  ...
  superator ":=" do |operand|
    if operand.kind_of? Hash
      ...
    else
      ...
    end
  end

更新:现在我看到需要在类之外定义运算符。是否可以定义这样的对象克隆运算符?


Update2更清晰的方法定义few,感谢 Joshua


参考

  1. http://www.linux-mag.com/cache/7432/1.html
  2. Ruby 是否支持像 PHP 这样的 var 引用?
  3. http://ruby.about.com/od/advancedruby/a/deepcopy.htm
4

1 回答 1

1

在你要求的地方a := b := c := AutoHash.new.few 3我认为(不确定我是否理解你的愿望)你真的想要a,b,c=Autohash.new.few 3


当您只使用第一个时,为什么很少有人使用可变参数?

我还发现您创建的返回值令人困惑,也许可以尝试

def few(n=0) 
  Array.new(n) { AutoHash.new } 
end 

除此之外,它似乎few应该是一个类方法。a,b,c=AutoHash.few 3如果您在课堂上定义很少,这将起作用:

def AutoHash.few(n=0)
  Array.new(n) { AutoHash.new }
end

如果a,b,c=AutoHash.few 3不是您想要的,并且您真的想实现自己的运算符,请查看Hacking parse.y,这是 RubyConf 2009 上的演讲。您可以在http://rubyconf2009 观看演示文稿。 confreaks.com/19-nov-2009-17-15-hacking-parsey-tatsuhiro-ujihisa.html您可以在http://www.slideshare.net/ujihisa/hacking-parsey-rubyconf-2009看到幻灯片

于 2010-07-02T12:21:44.580 回答