關於yield關鍵字的一些理解

在ruby中,爲什麼有些方法能夠接收參數變量又能接收代碼塊呢?這是因爲啊,這些方法有一種機制來傳輸這些代碼塊,運行完之後再返回。我們可以在一個方法中定義這樣一種機制,用yield關鍵字就可以啦。

看一下這段代碼:

def block_test
  puts "We're in the method!"
  puts "Yielding to the block..."
  yield
  puts "We're back in the method!"
end

block_test{puts "I'm yielding!"}
運行之後是這個樣子的:

We're in the method!
Yielding to the block...
I'm yielding!//代碼“注入”
We're back in the method!
==> nil
整體感覺就像是在一段代碼中注入了一段代碼的樣子

當然,強大的ruby還允許你注入的代碼得到一個參數變量,這樣就就能做更多事情了#^_^#

def yield_name(name)
  puts "In the method! Let's yield."
  yield name
  puts "Block complete! Back in the method."
end

# Now call the method with your name!
yield_name("Gonjay") {|myname| puts "My name is #{myname}."}
在yield_name方法運行到yield關鍵字的時候就傳了一個name參數給你之前丟過去的代碼塊,然後被你代碼塊中的myname所接收,最後打印出來

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章