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