詳解Ruby中的塊的知識_ruby專題

來源:互聯網
上載者:User

 文法:

block_name{  statement1  statement2  ..........}

在這裡,將學習如何通過使用一個簡單的 yield 語句調用塊。還將學習使用yield語句具有參數調用塊。將檢查的範例程式碼,這兩種類型的 yield 語句。
yield 語句:

讓我們來看看在yield語句的一個例子:

#!/usr/bin/rubydef test  puts "You are in the method"  yield  puts "You are again back to the method"  yieldendtest {puts "You are in the block"}

這將產生以下結果:

You are in the methodYou are in the blockYou are again back to the methodYou are in the block

也可以通過參數與屈服聲明。下面是一個例子:

#!/usr/bin/rubydef test  yield 5  puts "You are in the method test"  yield 100endtest {|i| puts "You are in the block #{i}"}

這將產生以下結果:

You are in the block 5You are in the method testYou are in the block 100

這裡的 yield 語句寫到後面跟著參數。甚至可以傳遞多個參數。在該塊中放置在兩條垂直線之間的變數(| |)接收的參數。因此,在上面的代碼中,yield5語句將試塊作為一個參數值5。

現在看看下面的語句:

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

在這裡,在變數i中的值為5。現在遵守以下 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/rubydef test yieldendtest{ puts "Hello world"}

這個例子是最簡單的方式來實現一個塊。調用塊 test 使用yield語句。
但是,如果最後一個參數的方法前面加上&,那麼可以通過一個塊這種方法,此塊將被分配到最後一個參數。

*和&在參數列表中&還在後面。

#!/usr/bin/rubydef test(&block)  block.callendtest { puts "Hello World!"}This will produce following result:Hello World!

BEGIN 和 END 塊

每一個Ruby源檔案都可以聲明的代碼塊作為檔案被載入運行(BEGIN塊)後,該程式已執行完畢(END塊)。

#!/usr/bin/rubyBEGIN {  # 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 blockMAIN code blockEND code block

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.