Ruby Print Inject Do Syntax

前端 未结 3 1582
执笔经年
执笔经年 2020-12-14 07:03

Why is it that the following code runs fine

p (1..1000).inject(0) { |sum, i|
    sum + i
}

But, the following code gives an error



        
3条回答
  •  粉色の甜心
    2020-12-14 07:26

    The block written using the curly braces binds to the inject method, which is what your intention is, and it will work fine.

    However, the block that is encapsulated in the do/end block, will bind to the p-method. Because of this, the inject call does not have an associated block. In this case, inject will interpret the argument, in this case 0, as a method name to call on every object. Bacuase 0 is not a symbol that can be converted into a method call, this will yield a warning.

提交回复
热议问题