【问题标题】:ruby - Pass a function that expects a function param to a functionruby - 将需要函数参数的函数传递给函数
【发布时间】:2023-01-12 17:13:07
【问题描述】:
def do_whatever # func A receives func B
    params = { test: 1 }
    proc = Proc.new{ puts "an important exec #{params[:test]}"; return "important response" } # func C
    yield(proc)
end

do_whatever do
    begin # func B
        resp = yield # executes func C
        puts resp
    rescue => e
        puts e
    end
end

嗨,我想要一个函数(例如 func A)传递一个函数块(例如 func B)并执行它。该函数块(例如函数 B)还接收在该函数中初始化的函数块(例如 func C)。在上面的代码中,我希望看到输出:

an important exec 1
important response

但是我得到了一个错误:没有给出块(产量)

【问题讨论】:

    标签: ruby lambda proc


    【解决方案1】:

    这应该可以解决问题:

    def do_whatever # func A receives func B
      params = { test: 1 }
      proc = Proc.new{ puts "an important exec #{params[:test]}"; next "important response" } # func C
      yield(proc)
    end
    
    do_whatever do |func_c|
      begin # func B
          resp = func_c.call
          puts resp
      rescue => e
          puts e
      end
    end
    

    当您在 do_whatever 中调用 yield 时,它作为参数传递给 do_whatever 的块,并将 proc 作为参数返回给块。由于 return 在 Procs 中不起作用,您需要使用 next 代替。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2012-09-15
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      相关资源
      最近更新 更多