【问题标题】:How do i return a block of code in ruby如何在 ruby​​ 中返回一段代码
【发布时间】:2014-03-11 23:31:40
【问题描述】:

我想从一个函数返回一个多行代码块,由另一个函数执行

例如

def foo 
  return #block
end

def bar(&block)
  block.call
end

bar(foo)

有人知道怎么做吗? 红宝石 1.9.3

【问题讨论】:

  • 你想做什么?可能有更好的方法。

标签: ruby return block


【解决方案1】:

您需要创建一个 Proc。有几种方法可以创建它们——主要是proclambda->。您只需将一个块传递给这些函数之一,它将将该块包装在一个 Proc 对象中。 (这三种方法处理参数的方式存在细微差别,但您通常不需要关心。)因此您可以这样写:

def foo 
  proc { puts "Look ma, I got called!" }
  # you don't need the return keyword in Ruby -- the last expression reached returns automatically
end

def bar(&block)
  block.call
end

bar(&foo) # You need the & operator to convert the Proc back into a block

【讨论】:

    【解决方案2】:

    你可以返回一个Proc对象:

    def foo
        return Proc.new { ... }
    end
    
    def bar(block)
        block.call
    end
    
    bar(foo)
    

    Here 是活生生的例子。

    【讨论】:

    • 如果方法采用块并根据需要与 Proc 相互转换会更自然。
    【解决方案3】:
    def foo 
      Proc.new {
        # code here
      } 
    end
    

    不用return,它是隐式的。

    【讨论】:

    • @Jefffrey - 不在红宝石中。我发现一些开发人员过度使用return 语句,他们错过了一些方法返回他们不期望的结果(尤其是 before_save 挂钩中的常见错误)
    • 在我看来,return 几乎应该只用在方法的第一行或第二行,当你检查参数或者什么都不需要做的时候。如果我在不需要时看到显式返回,这会让我感到困惑(以及我认为最有经验的 Ruby 程序员)
    猜你喜欢
    • 2016-10-19
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多