我如何在 ruby​​ 中返回一个代码块

use*_*397 4 ruby return block

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

例如

def foo 
  return #block
end

def bar(&block)
  block.call
end

bar(foo)
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?红宝石 1.9.3

Chu*_*uck 6

您需要创建一个 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
Run Code Online (Sandbox Code Playgroud)