欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Ruby中的塊的知識(shí)

 更新時(shí)間:2015年05月12日 10:52:27   投稿:goldensun  
這篇文章主要介紹了詳解Ruby中的塊的知識(shí),包括yield語(yǔ)句和begin/end塊等知識(shí)點(diǎn),需要的朋友可以參考下

 語(yǔ)法:

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

在這里,將學(xué)習(xí)如何通過使用一個(gè)簡(jiǎn)單的 yield 語(yǔ)句調(diào)用塊。還將學(xué)習(xí)使用yield語(yǔ)句具有參數(shù)調(diào)用塊。將檢查的示例代碼,這兩種類型的 yield 語(yǔ)句。
yield 語(yǔ)句:

讓我們來看看在yield語(yǔ)句的一個(gè)例子:

#!/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"}

這將產(chǎn)生以下結(jié)果:

You are in the method
You are in the block
You are again back to the method
You are in the block

也可以通過參數(shù)與屈服聲明。下面是一個(gè)例子:

#!/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}"}

這將產(chǎn)生以下結(jié)果:

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

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

現(xiàn)在看看下面的語(yǔ)句:

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

在這里,在變量i中的值為5?,F(xiàn)在遵守以下 puts 語(yǔ)句:

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

puts 語(yǔ)句的輸出是:

You are in the block 5

如果想超過一個(gè)參數(shù),然后yield語(yǔ)句就變成了:

yield a, b

那么塊是:

test {|a, b| statement}

這些參數(shù)將用逗號(hào)隔開。
塊和方法:

我們已經(jīng)看到了如何將一個(gè)塊和方法關(guān)聯(lián)。通常調(diào)用塊從塊具有相同名稱的方法,通過使用yield語(yǔ)句。因此,編寫:

#!/usr/bin/ruby

def test
 yield
end
test{ puts "Hello world"}

這個(gè)例子是最簡(jiǎn)單的方式來實(shí)現(xiàn)一個(gè)塊。調(diào)用塊 test 使用yield語(yǔ)句。
但是,如果最后一個(gè)參數(shù)的方法前面加上&,那么可以通過一個(gè)塊這種方法,此塊將被分配到最后一個(gè)參數(shù)。

*和&在參數(shù)列表中&還在后面。

#!/usr/bin/ruby

def test(&block)
  block.call
end
test { puts "Hello World!"}

This will produce following result:

Hello World!

BEGIN 和 END 塊

每一個(gè)Ruby源文件都可以聲明的代碼塊作為文件被加載運(yùn)行(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"

一個(gè)程序可能包括多個(gè)BEGIN和END塊。 BEGIN塊以遇到它們的順序執(zhí)行。 END塊以相反的順序執(zhí)行。上述程序執(zhí)行時(shí),會(huì)產(chǎn)生以下結(jié)果:

BEGIN code block
MAIN code block
END code block

相關(guān)文章

最新評(píng)論