def box contents = nil get = Proc.new {contents} set = Proc.new {|n| contents = n} return get, set end
reader, writer = box puts reader.call #nil puts writer.call(2) #2 puts reader.call #2
上面 box 里面为什么要弄个 get 呢?如果 get 和 set 对调下位置下面输出全是 nil?可是如果改成下面这样又有问题:
def box contents = nil #get = Proc.new {contents} set = Proc.new {|n| contents = n} return set end
reader, writer = box puts reader.call #nil puts writer.call(2) #warning: multiple values for a block parameter (0 for 1) puts reader.call #undefined method `call' for nil:NilClass (NoMethodError)
3 个问题求解