2013-03-20 48 views
0

我有这样的λ:我如何正确范围Ruby 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 

我想将它传递给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' 

但是当我运行my_funky_lambda.rb这个拉姆达方法,我得到一个NameError。我不确定这个lambda的范围有什么问题,但我似乎无法从is_there_an_echo_in_here访问它。

echo_word适当的作用域和使用,如果我把它作为常量ECHO_WORD并像这样使用它,但必须有一个更直接的解决方案。

在这种情况下,访问is_there_an_echo_in_here内部的echo_word lamba的最佳方式是什么?将它包装在一个模块中,访问全局范围,还有其他的东西?

+0

创建一个最小的测试情况下,在一个代码块。那么你应该看到这个问题。它与'echo_word'的范围(或缺少)有关。没有关于lambda的信息。也可能是'x = 2; .. def y;做放x结束'显示这个问题。 – 2013-03-20 21:29:55

+0

哈哈公平点。看起来我已经花费了太多时间在节点上,并将其与:var a = 1; var b = function(){console.log(a); }; B()' – Hugo 2013-03-20 21:36:33

回答

5

在Ruby中,常规方法不是闭包。正因为如此,您不能拨打内部is_there_an_echo_in_here

但是,块是关闭的。在Ruby 2+,你可以这样做:

define_method(:is_there_an_echo_in_here) do |*args| 
    args.each &echo_word 
end 

另一种方式是通过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