Ruby - 程式碼塊



您已經瞭解了 Ruby 如何定義方法,您可以在其中放置多條語句,然後呼叫該方法。類似地,Ruby 有一個程式碼塊的概念。

  • 程式碼塊由程式碼塊組成。

  • 您為程式碼塊分配一個名稱。

  • 程式碼塊中的程式碼始終用大括號({})括起來。

  • 程式碼塊總是從與程式碼塊名稱相同的函式中呼叫。這意味著如果您有一個名為test的程式碼塊,那麼您使用函式test來呼叫此程式碼塊。

  • 您可以使用yield語句呼叫程式碼塊。

語法

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

您也可以使用 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 語句將值 5 作為引數傳遞給 test 程式碼塊。

現在,看一下下面的語句:

test {|i| puts "You are in the block #{i}"}

在這裡,值 5 接收在變數i中。現在,觀察下面的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!

BEGIN 和 END 程式碼塊

每個 Ruby 原始檔都可以宣告要在載入檔案時執行的程式碼塊(BEGIN 程式碼塊)以及在程式執行完畢後執行的程式碼塊(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 程式碼塊按遇到的順序執行。END 程式碼塊按相反順序執行。執行後,上述程式產生以下結果:

BEGIN code block
MAIN code block
END code block
廣告
© . All rights reserved.