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
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