Enumerator yielder.yield 與 Proc.yield 區別

c3tc3tc3t發表於2016-01-09

最近看ruby cookbook遇到這個用法,google一下,這裡原文解釋

http://stackoverflow.com/questions/18865860/enumerator-yielder-yield-vs-proc-yield

 

Enumerator yielder.yield VS Proc.yield

The yield statement has no receiver. Inside a method it means "Run the block right now". An error occurs if no block is attached. It is not always given an argument, because sometimes you just want to run the block.

就是說。有時候未必會傳遞一個block。僅僅是想執行一個block。但是未必會傳遞這個block,這時yielder.yield派上用場

例如

def foo
yield :bar
end
foo # LocalJumpError
foo { |x| puts x } # bar

Enumerator::Yielder
For a yielder, yield is almost always given an argument. That's because it means the same as << which is "The next time someone calls next on me, give them this value".

yield總是會得到一個引數, 因為<<和yield一樣意思,下一次在我身上呼叫next方法,返回這個值

Enumerator.new { |yielder| yielder.yield 3 }.next # 3 #返回3
Enumerator.new { |yielder| yielder << 3 }.next # same thing

Proc
Procs and lambdas are basically functions. yield here means the same thing as call, which "Just call the function". You can give it an argument or not, depending on how the proc was defined. Nothing fancy here.

procs和lambda類似函式,yield和call作用一樣,呼叫這個函式 你可以傳遞或者不傳遞引數,這個傳不傳按照proc怎麼定義來看,
proc { |x| puts x }.yield(:bar) # bar
proc { |x| puts.x }.call(:bar) # same thing

相關文章