語法:
block_name{
statement1
statement2
..........
}
在這里,將學習如何通過使用一個簡單的 yield 語句調用塊。還將學習使用yield語句具有參數調用塊。將檢查的示例代碼,這兩種類型的 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"}
這將產生以下結果:
You are in the method
You are in the block
You are again back to the method
You are in the block
也可以通過參數與屈服聲明。下面是一個例子:
#!/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}"}
這將產生以下結果:
You are in the block 5
You are in the method test
You are in the block 100
這里的 yield 語句寫到后面跟著參數。甚至可以傳遞多個參數。在該塊中放置在兩條垂直線之間的變量(| |)接收的參數。因此,在上面的代碼中,yield5語句將試塊作為一個參數值5。
現(xiàn)在看看下面的語句:
test {|i| puts "You are in the block #{i}"}
在這里,在變量i中的值為5?,F(xiàn)在遵守以下 puts 語句:
puts "You are in the block #{i}"
puts 語句的輸出是:
如果想超過一個參數,然后yield語句就變成了:
那么塊是:
這些參數將用逗號隔開。
塊和方法:
我們已經看到了如何將一個塊和方法關聯(lián)。通常調用塊從塊具有相同名稱的方法,通過使用yield語句。因此,編寫:
#!/usr/bin/ruby
def test
yield
end
test{ puts "Hello world"}
這個例子是最簡單的方式來實現(xiàn)一個塊。調用塊 test 使用yield語句。
但是,如果最后一個參數的方法前面加上&,那么可以通過一個塊這種方法,此塊將被分配到最后一個參數。
*和&在參數列表中&還在后面。
#!/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í)行時,會產生以下結果:
BEGIN code block
MAIN code block
END code block
您可能感興趣的文章:- Ruby中的block代碼塊學習教程
- 詳解Ruby中的代碼塊對象Proc
- Ruby中編寫類與模塊的風格指南
- Ruby中關于模塊的一些基礎知識
- 介紹Ruby中的模塊與混合類型的相關知識
- Ruby中使用SWIG編寫ruby擴展模塊實例
- 使用Ruby re模塊創(chuàng)建復雜的正則表達式
- ruby 模塊
- 深入理解Ruby中的代碼塊block特性