詳解Ruby中的塊的知識
語法:
block_name{ statement1 statement2 .......... }
在這里,將學習如何通過使用一個簡單的 yield 語句調(diào)用塊。還將學習使用yield語句具有參數(shù)調(diào)用塊。將檢查的示例代碼,這兩種類型的 yield 語句。
yield 語句:
讓我們來看看在yield語句的一個例子:
#!/usr/bin/ruby def test puts "You are in the method" yield puts "You are again back to the method" yield end test {puts "You are in the block"}
這將產(chǎn)生以下結果:
You are in the method You are in the block You are again back to the method You are in the block
也可以通過參數(shù)與屈服聲明。下面是一個例子:
#!/usr/bin/ruby def test yield 5 puts "You are in the method test" yield 100 end test {|i| puts "You are in the block #{i}"}
這將產(chǎn)生以下結果:
You are in the block 5 You are in the method test You are in the block 100
這里的 yield 語句寫到后面跟著參數(shù)。甚至可以傳遞多個參數(shù)。在該塊中放置在兩條垂直線之間的變量(| |)接收的參數(shù)。因此,在上面的代碼中,yield5語句將試塊作為一個參數(shù)值5。
現(xiàn)在看看下面的語句:
test {|i| puts "You are in the block #{i}"}
在這里,在變量i中的值為5。現(xiàn)在遵守以下 puts 語句:
puts "You are in the block #{i}"
puts 語句的輸出是:
You are in the block 5
如果想超過一個參數(shù),然后yield語句就變成了:
yield a, b
那么塊是:
test {|a, b| statement}
這些參數(shù)將用逗號隔開。
塊和方法:
我們已經(jīng)看到了如何將一個塊和方法關聯(lián)。通常調(diào)用塊從塊具有相同名稱的方法,通過使用yield語句。因此,編寫:
#!/usr/bin/ruby def test yield end test{ puts "Hello world"}
這個例子是最簡單的方式來實現(xiàn)一個塊。調(diào)用塊 test 使用yield語句。
但是,如果最后一個參數(shù)的方法前面加上&,那么可以通過一個塊這種方法,此塊將被分配到最后一個參數(shù)。
*和&在參數(shù)列表中&還在后面。
#!/usr/bin/ruby def test(&block) block.call end test { puts "Hello World!"} This will produce following result: Hello World!
BEGIN 和 END 塊
每一個Ruby源文件都可以聲明的代碼塊作為文件被加載運行(BEGIN塊)后,該程序已執(zhí)行完畢(END塊)。
#!/usr/bin/ruby BEGIN { # BEGIN block code puts "BEGIN code block" } END { # END block code puts "END code block" } # MAIN block code puts "MAIN code block"
一個程序可能包括多個BEGIN和END塊。 BEGIN塊以遇到它們的順序執(zhí)行。 END塊以相反的順序執(zhí)行。上述程序執(zhí)行時,會產(chǎn)生以下結果:
BEGIN code block MAIN code block END code block
相關文章
在Ruby on Rails中優(yōu)化ActiveRecord的方法
這篇文章主要介紹了在Ruby on Rails中優(yōu)化ActiveRecord的方法,本文來自于IBM官方網(wǎng)站技術文檔,需要的朋友可以參考下2015-04-04利用RJB在Ruby on Rails中使用Java代碼的教程
這篇文章主要介紹了利用RJB在Ruby on Rails中使用Java代碼的教程,本文來自于IBM官方網(wǎng)站技術文檔,需要的朋友可以參考下2015-04-04