开发者

Is the ruby Enumerable.Inject method a closure or just a block?

开发者 https://www.devze.com 2023-03-04 00:08 出处:网络
开发者_如何学JAVAI have been trying to understand if you need to create a proc or lambda before something is a closure in Ruby or not.
开发者_如何学JAVA

I have been trying to understand if you need to create a proc or lambda before something is a closure in Ruby or not.

As a canonical example we can look at the inject method. It's using the yield keyword but is it a closure or just a block?

def inject(init)
  result = init
  each do |item|
    result = yield(result, item)
  end
  result
end


A piece of code is a closure if it captures the enclosing scope, which a block does, so blocks (as well as lambdas and procs) are closures.

Methods defined using def however, don't close over anything, so inject is not a closure.

0

精彩评论

暂无评论...
验证码 换一张
取 消