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)
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 1003.传递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.
- ruby methods block moudle 2
- ruby methods block moudle 1
- ruby methods block moudle 3
- Kernel Methods in Ruby
- rhyming methods(ruby)
- [Ruby] Define abstract methods
- Ruby Block
- ruby学习笔记(三)--ruby methods
- Ruby | Block和迭代器
- Amazing ruby: block & yield
- Ruby的Block
- ruby block & proc & lambda
- 浅析Ruby中的methods,private_methods和instance_methods
- ruby中的block和迭代器
- Ruby 中的 block、proc、lambda
- ruby 中的Block,lambda,Proc
- ruby中的 Proc、block说明
- Ruby 中的 block、proc、lambda
- excel导入数据
- php中的魔术方法
- hdu4556(欧拉函数)
- OK6410——NFS挂载
- 如何修改Linux的环境变量
- ruby methods block moudle 2
- Linux下NandFlash的驱动编写(1)
- Linux 0.12 OS. block - ll_rw_blk.c
- 省流量没尴尬 Connectify中文版轻松上网
- Eclipse3.6 加中文包后自动提示/补全信息显示错误
- oracle sql中查询ip段内的记录
- 群联PS2251-67成功量产教程
- Git常用操作命令
- Spring MVC 中的基于注解的 Controller