How to "glue in" a lambda inside another lambda body?

时间:2018-06-04 16:51:26

标签: ruby lambda

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?

1 个答案:

答案 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