How to require a block in Ruby?

前端 未结 3 1375
长情又很酷
长情又很酷 2021-01-01 13:47

Is there any built in way to require that a block be passed to a Ruby method? I realize I can just raise an exception if block_given? is false, but is there so

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-01 14:43

    If your method required a block, Ruby will prompt it. The raise keyword doesn't require a block, it only prompts a message for handling an Exception.

    It could be a method like the above example

    def needs_block
     yield
    end
    

    needs_block

    Or you could require a Proc

    def needs_block(&Proc)
        proc.call
    end
    

    Anyway, adding raise block_given? would be nice.

    Here says:

    "The raise method is from the Kernel module. By default, raise creates an exception of the RuntimeError class. To raise an exception of a specific class, you can pass in the class name as an argument to raise".

提交回复
热议问题