rubylambdaproc

ruby - Pass a function that expects a function param to a function


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

Hi, I want a function (e.g. func A) to be passed a block of function (e.g. func B) and executes it. That block of function (e.g. function B) also receives a block of function (e.g. func C) that is initialized in that function. On above code, I expect to see the output:

an important exec 1
important response

but instead I got an error: no block given (yield)


Solution

  • This should do the trick:

    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
    

    When you call yield inside do_whatever that is passed as the argument to the block of do_whatever, and returns the proc as an argument to block. Since return does not work in Procs, you will need to use next instead.