新手问题 请教变量共享问题

wzhang1987 · January 15, 2013 · Last by i5ting replied at January 15, 2013 · 1958 hits

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 个问题求解

编辑一下样式吧。列出 123.。。。

You need to Sign in before reply, if you don't have an account, please Sign up first.