您已經知道 Ruby 如何定義方法以及您如何調用方法。類似地,Ruby 有一個塊的概念。
block_name{
statement1
statement2
..........
}
在這里,您將學到如何使用一個簡單的 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
您也可以傳遞帶有參數的 yield 語句。下面是一個實例:
#!/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 語句后跟著參數。您甚至可以傳遞多個參數。在塊中,您可以在兩個豎線之間放置一個變量來接受參數。因此,在上面的代碼中,yield 5 語句向 test 塊傳遞值 5 作為參數。
現在,看下面的語句:
test {|i| puts "You are in the block #{i}"}
在這里,值 5 會在變量 i 中收到?,F在,觀察下面的 puts 語句:
puts "You are in the block #{i}"
這個 puts 語句的輸出是:
You are in the block 5
如果您想要傳遞多個參數,那么 yield 語句如下所示:
yield a, b
此時,塊如下所示:
test {|a, b| statement}
參數使用逗號分隔。
您已經看到塊和方法之間是如何相互關聯的。您通常使用 yield 語句從與其具有相同名稱的方法調用塊。因此,代碼如下所示:
#!/usr/bin/ruby
def test
yield
end
test{ puts "Hello world"}
本實例是實現塊的最簡單的方式。您使用 yield 語句調用 test 塊。
但是如果方法的最后一個參數前帶有 &,那么您可以向該方法傳遞一個塊,且這個塊可被賦給最后一個參數。如果 * 和 & 同時出現在參數列表中,& 應放在后面。
#!/usr/bin/ruby
def test(&block)
block.call
end
test { puts "Hello World!"}
這將產生以下結果:
Hello World!
每個 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