Ruby Print Inject Do Syntax

前端 未结 3 1595
执笔经年
执笔经年 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:14

    This looks like a effect of the difference in binding between do/end and brackets:

    brackets, used as you are above, will bind to the last function chained while do/end will bind to the first.

    I think thats sort of a odd way to say it, but basically the first instance is passing the block to the function 'inject', while the second is actually trying to pass the block to the first method 'p'.

提交回复
热议问题