我有以下的關閉:追加到外部變量在封閉
def func
def inner_func
list << 3 # how to append an element to the outer `list`?
end
list = []
inner_func
list
end
我不知道我怎樣才能從inner_func
追加東西list
,如上面的嘗試是錯誤的。
我有以下的關閉:追加到外部變量在封閉
def func
def inner_func
list << 3 # how to append an element to the outer `list`?
end
list = []
inner_func
list
end
我不知道我怎樣才能從inner_func
追加東西list
,如上面的嘗試是錯誤的。
使用實例方法,像這樣:
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
感謝您的詳細解答! – linkyndy
Ruby的問題在於它看起來像它支持嵌套方法,但它並不像Piotr指出的那樣。你可以使用例如。儘管如此,如http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html – EdvardM
中所示我明白。讓你指出如何在我的情況下使用特效?另外,'inner_func'實際上是一個更大的東西,是否將所有東西都放在proc中是正確的? – linkyndy