Say I have such two lambdas in Ruby:
lambda1 = -> { puts 'lambda1' }
lambda2 = -> {
puts 'lambda2 calls lambda1'
lambda1.()
}
It works as expected:
lambda1.()
# lambda1
lambda2.()
# lambda2 calls lambda1
# lambda1
But now if I remove lambda1
, lambda2
will stop working:
lambda1 = nil
lambda2.()
NoMethodError: undefined method `call' for nil:NilClass
What can I do to "glue in" my lambda1
to lambda2
to make the first an inherent part of the second and avoid that situation?
答案 0 :(得分:5)
问题是,您的# vi /etc/mysql/my.cnf
#socket = /var/lib/mysql/mysql.sock
# service mysql restart
会在闭包中捕获变量lambda2
,因此会在lambda1
稍后更改时发现。解决方案只是让它捕获一个不同的变量:
lambda1
“但这也有同样的问题!”你可能会说,“我可以通过重新分配lambda1 = -> { puts 'lambda1' }
x = lambda1 # copy the reference
lambda2 = -> { x.() }
lambda1 = nil
lambda2.()
来打破它!”好吧,然后使它x
受范围保护:
x