国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Ruby > 正文

詳解Ruby中的塊的知識

2020-10-29 19:39:56
字體:
來源:轉載
供稿:網友

 語法:

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桦甸市| 新竹县| 元谋县| 昭平县| 陕西省| 青浦区| 岫岩| 元阳县| 武汉市| 七台河市| 从江县| 承德市| 沾化县| 兰考县| 阿克苏市| 扎囊县| 精河县| 墨脱县| 河池市| 昌图县| 德令哈市| 贵德县| 三明市| 乌兰县| 安顺市| 龙游县| 上蔡县| 蒙自县| 鸡泽县| 镇江市| 日照市| 光山县| 克什克腾旗| 宁城县| 开原市| 武城县| 阿瓦提县| 安阳市| 闽清县| 盈江县| 福泉市|