『Ruby』块(Block)
发布日期:2021-06-28 20:00:30
浏览次数:2
分类:技术文章
本文共 2282 字,大约阅读时间需要 7 分钟。
文章目录
一、块的表示
Ruby的块又称为代码块,它总是从与其具有相同名称的函数调用,在同名函数中使用yield调用
以下是一个块的简单定义
def block do endblock{ do1 do2 ...}
块不能被单独定义,否则报错,它总是与同名函数一起出现
block{ puts "Inside the block 1"}
undefined method `block' for main:Object (NoMethodError)
二、块的调用
yield
如上所示,如果要调用块,使用yield
若省略了yield,函数被调用了但是没有进块内
def block puts "Inside the function" puts "Inside the function"endblock{ puts "Inside the block"}
Inside the functionInside the function
如果是需要传参的函数,同理
def block(a) puts "Inside the function #{ a}" yield puts "Inside the function #{ a}"endblock(1){ puts "Inside the block"}
Inside the function 1Inside the blockInside the function 1
可以定义多个同名块
def block(a) puts "Inside the function #{ a}" yield puts "Inside the function #{ a}"endblock(1){ puts "Inside the block 1"}putsblock(2){ puts "Inside the block 2"}
Inside the function 1Inside the block 1Inside the function 1Inside the function 2Inside the block 2Inside the function 2
因此:如果定义了块,默认调用一次同名的函数,如果出现yield,则进入块内
argv.call
除了yield还支持&argv
传入块,然后使用argv.call
调用
def test(i,&block) puts "Inside the function #{ i}" block.callendtest(1){ puts 'Inside the block'}
Inside the function 1Inside the block
三、块传参
如果要对块传入参数,需要在yield跟随参数,并且在块使用竖线表示接收传参
以下是错误的
def block(a) puts "Inside the function #{ a}" yield puts "Inside the function #{ a}"endblock(1){ puts "Inside the block #{ a}"}
Inside the function 1script.rb:11:in `block in': undefined local variable or method `a' for main:Object (NameError) from script.rb:6:in `block' from script.rb:10:in ` 'Exited with error status 1
以下是正确将参数传入块的操作,多个参数用逗号分隔即可
def block(a) puts "Inside the function #{ a}" yield a puts "Inside the function #{ a}"end# |a|表示接收参数block(1){ |a| puts "Inside the block #{ a}"}
Inside the function 1Inside the block 1Inside the function 1
call传参也是同理
def test(i,&block) puts "Inside the function #{ i}" block.call(i)endtest(1){ |i| puts "Inside the block #{ i}"}
四、特殊块——BEGIN和END
Ruby 源文件可以声明当文件被加载时要运行的代码块(BEGIN 块),以及程序完成执行后要运行的代码块(END 块)。一个程序可以包含多个 BEGIN 和 END 块。BEGIN 块按照它们出现的顺序执行。END 块按照它们出现的相反顺序执行。
BEGIN { puts "BEGIN 1"} BEGIN { puts "BEGIN 2"} puts "MAIN 3"END { puts "END 5"}END { puts "END 4"}
BEGIN 1BEGIN 2MAIN 3END 4END 5
完
转载地址:https://blog.csdn.net/Xxy605/article/details/117733768 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月03日 16时14分33秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
servlet与jsp实现动态验证码
2019-04-29
jsp简介
2019-04-29
c/s角度看待JavaBean,及关于内省
2019-04-29
mysql常用命令
2019-04-29
DBUtils原理及基本使用
2019-04-29
jsp分页技术的实现
2019-04-29
监听器与过滤器
2019-04-29
servlet之文件上传与下载功能实现
2019-04-29
JQuery入门案例讲解
2019-04-29
Js原生Ajax和Jquery的Ajax
2019-04-29
hibernate的环境搭建及简单的增删改查
2019-04-29
Hibernate实体类创建注意事项
2019-04-29
hibernate主键
2019-04-29
Hibernate使用c3p0连接池
2019-04-29
Hibernate关于一对多 多对一 多对多关联关系的设置
2019-04-29
HQL
2019-04-29
Hibernate查询优化
2019-04-29
装饰者模式的应用
2019-04-29
Struts2框架搭建
2019-04-29
struts2动态方法调用之参数占位符动态调用
2019-04-29