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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值