Ruby: Proc#call vs yield

后端 未结 6 1478
野性不改
野性不改 2020-12-02 05:54

What are the behavioural differences between the following two implementations in Ruby of the thrice method?

module WithYield
  def self.thrice
         


        
6条回答
  •  感动是毒
    2020-12-02 06:37

    They give different error messages if you forget to pass a block:

    > WithYield::thrice
    LocalJumpError: no block given
            from (irb):3:in `thrice'
            from (irb):3:in `times'
            from (irb):3:in `thrice'
    
    > WithProcCall::thrice
    NoMethodError: undefined method `call' for nil:NilClass
            from (irb):9:in `thrice'
            from (irb):9:in `times'
            from (irb):9:in `thrice'
    

    But they behave the same if you try to pass a "normal" (non-block) argument:

    > WithYield::thrice(42)
    ArgumentError: wrong number of arguments (1 for 0)
            from (irb):19:in `thrice'
    
    > WithProcCall::thrice(42)
    ArgumentError: wrong number of arguments (1 for 0)
            from (irb):20:in `thrice'
    

提交回复
热议问题