【问题标题】:How do I properly scope a Ruby lambda?如何正确确定 Ruby lambda 的范围?
【发布时间】:2013-03-20 21:24:09
【问题描述】:

我有这个 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'

但是当我使用这个 lambda 方法运行 my_funky_lambda.rb 时,我得到了一个 NameError。我不确定这个 lambda 的作用域是什么,但我似乎无法从 is_there_an_echo_in_here 访问它。

如果我将ECHO_WORD 设为常量ECHO_WORD 并像这样使用它,则echo_word 的范围和使用是正确的,但必须有一个更直接的解决方案。

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

【问题讨论】:

  • 在一个代码块中创建一个最小的测试用例。然后你应该看到这个问题。它与echo_word 的范围(或缺乏)有关。没有什么关于 lambdas 的。还不如x = 2; .. def y; do puts x end 来显示这个问题。
  • 大声笑公平点。看起来我在节点领域花费了太多时间并将其与以下内容混淆:var a = 1; var b = function() { console.log(a); }; b()

标签: ruby lambda


【解决方案1】:

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

然而,块是闭包。在 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

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2020-03-05
    • 2017-01-20
    相关资源
    最近更新 更多