Ruby Print Inject Do Syntax

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

    The problem is with the p at the beginning. If you omit these you'll see that both work fine:

    # Works!
    [5, 6, 7].inject(0) do |sum, i| # Correctly binds to `inject`.
      sum + i
    end
    
    # Works too!
    [5, 6, 7].inject(0) { |sum, i|  # Correctly binds to `inject`.
      sum + i
    }
    

    But this won't work:

    # Kablammo! "p" came first, so it gets first dibs on your do..end block.
    # Now inject has no block to bind to!
    p [5, 6, 7].inject(0) do |sum, i|   # Binds to `p` -- not what you wanted.
      sum + i
    end
    

提交回复
热议问题