附加到闭包中的外部变量

Append to an outer variable in a closure

我有以下闭包:

def func
  def inner_func
    list << 3 # how to append an element to the outer `list`?
  end

  list = []
  inner_func
  list
end

我不确定如何从 inner_funclist 添加内容,因为上述尝试是错误的。

使用实例方法,像这样:

def func
  def inner_func
    @list << 3 # how to append an element to the outer `list`?
  end

  @list = []
  inner_func
  @list
end

不过请看一下 this - 关于 Ruby 和嵌套方法。

干净解决方法示例:

def func
  list = []
  inner_func list # => [3]
  inner_func list # => [3, 3]
end

def inner_func(list)
  list << 3
end

Ruby 没有嵌套方法。它确实有 lambda,恰好是闭包。

def func
  list = []
  l = ->{ list << 3}
  l.call
  p list
end

func # => [3]