ruby methods block moudle 2

来源:互联网 发布:ubuntu tty1 login 编辑:程序博客网 时间:2024/05/07 01:59

开始看block时,习惯性的把它与java中的静态块,代码块弄混淆,java中的静态块通常用于一些静态变量的初始化,当然在测试中可以同时使用@before @after的注解方式让一些方法在执行前后执行。

其实再一开始学习的时候,就了解了过block begin 和end,这里复习下,顺便学习下具体该怎么用:

BEGIN {    begin block code } END {    end block code }
在每一个ruby的源文件中可以定义许多block块,当运行这些block时,它会先加载begin块,运行结束后会加载end块。

1.什么叫block,block包含什么?

  • A block consists of chunks of code.(一个block块包含着一些代码)

  • You assign a name to a block.(一个block有一个名称)

  • The code in the block is always enclosed within braces ({}).(一个block总是{}围起来)(这个比较容易和方法区分)

  • 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 name test, then you use the function test to invoke this block.(一个block总是和一个方法相对应的,有一个名字为test的block,你需要一个test方法去调用它)

  • You invoke a block by using the yield statement.(需要yield语句调用一个block)

看到定义就可以找到method和block的区别,和他们之间的关系了。具体怎么样呢,必须通过手动敲代码才能更好的理解

def 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
有什么感觉吗?去掉test{}块,该段代码不会有任何结果,没有被调用。test调用将yield地方换成了对应的自己了。

2.给block中传递参数

def 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
3.传递block

def test(&block)   block.callendtest { puts "Hello World!"}
有一段英文说明有待理解:

 if the last argument of a method is preceded by &, then you can pass a block to this method and this block will be assigned to the last parameter. In case both * and & are present in the argument list, & should come later.






原创粉丝点击