我有这个lambda:
echo_word = lambda do |words|
  puts words
  many_words = /\w\s(.+)/
    2.times do
      sleep 1
      match = many_words.match(words)
      puts match[1] if match
    end
  sleep 1
end
Run Code Online (Sandbox Code Playgroud)
我希望将它each作为一个块传递给它,并且将来每个块都会更多.
def is_there_an_echo_in_here *args
  args.each &echo_word # throws a name error
end
is_there_an_echo_in_here 'hello out there', 'fun times'
Run Code Online (Sandbox Code Playgroud)
但是当我用这个lambda方法运行my_funky_lambda.rb时,我得到一个NameError.我不确定这个lambda的范围是什么,但我似乎无法访问它is_there_an_echo_in_here.
echo_word如果我使它成为常量ECHO_WORD并使用它就适当地限定和使用,但必须有一个更直接的解决方案.
在这种情况下,echo_word从内部访问lamba 的最佳方法是什么is_there_an_echo_in_here,例如将其包装在模块中,访问全局范围,还有其他什么?
在Ruby中,常规方法不是闭包.因为这个原因你不能打电话echo_word进去is_there_an_echo_in_here.
然而,块是封闭的.在Ruby 2+中,你可以这样做:
define_method(:is_there_an_echo_in_here) do |*args|
  args.each &echo_word
end
Run Code Online (Sandbox Code Playgroud)
另一种方式是echo_word作为参数传递:
def is_there_an_echo_in_here *args, block
  args.each &block
end
is_there_an_echo_in_here 'hello out there', 'fun times', echo_word
Run Code Online (Sandbox Code Playgroud)