Ruby Blocks

 

Ruby Blocks

 

 

Block構成

A block consists of chunks of code.

You assign a name to a block.

The code in the block is always enclosed within braces ({}).

A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the nametest, then you use the function?test?to invoke this block.

You invoke a block by using the?yield?statement.

 

語法:

block_name{

  statement1

  statement2

  ..........

}

 

Here you will learn to invoke a block by using a simple?yield?statement. You will also learn to use a?yield?statement with parameters for invoking a block. You will check the sample code with both types of?yield?statements.

使用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

 

 

有參數

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

 

在Block塊中,使用兩個豎線來表示接收的參數

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

如果接收多個參數

test {|a, b| statement}

 

Blocks and Methods:

 

塊與方法

def test

 yield

end

test{ puts "Hello world"}

 

block作爲參數,使用"&"符號,被當作一個Proc對象來處理,利用自身的call方法來進行調用 

def test(&block)

  block.call

end

test { puts "Hello World!"}

結果

Hello World!

 

 

BEGIN and END Blocks

 

BEGIN Blocks

一般置於文件開始位置,優於其它代碼先執行,不受制於程序的邏輯運行。

 

END Blocks

程序結束時運行,END塊受制於程序的邏輯運行。

 

多個BEGIN Blocks時,按聲明順序執行

多個END Blocks時,正好相反



Ref:

Ruby Blocks

http://www.tutorialspoint.com/ruby/ruby_blocks.htm

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章