Ruby--块(Block)与模块(Module)
来源:互联网 发布:知乎周刊纸质版 编辑:程序博客网 时间:2024/05/18 01:10
1、块(Block)
定义:首先从中文的字面理解到就是一整块,联想到编码我们便能想到这可能是一些代码的一整块构成吧。没错!*A Ruby block is a way of grouping statements*-- Ruby中的块就是组织多个代码句的一种方式。表示:Ruby标准中,对于单行的代码块使用大括号‘{}’表示;对于多行的代码块则使用do..end表示。用法: A. 方法与块关联 代码块作为参数传递给方法,使用yield关键字执行代码块。
def test_method puts "this is test_method" #使用 yield 关键词调用块 yield puts "this is test_method again" yield end #代码块一般只出现在与方法调用相近的地方 test_method { puts "this is block"} #输出的结果如下: knightdeMacBook-Pro:ruby knight$ ruby test.rb this is test_method this is block this is test_method again this is block
B. yield传入参数的使用
def test_method puts "this is test_method" #yield传入参数 yield("hello ", "world") puts "this is test_method again" yield(1, 2) end #代码块一般只出现在与方法调用相近的地方 test_method { |str1, str2| puts str1 + str2} #输出内容 knightdeMacBook-Pro:ruby knight$ ruby test.rb this is test_method hello world this is test_method again 3
2、模块(Module)
定义:模块是类、方法和常量的集合,类似类但是不像类可以实例化以及继承等。 用途:模块有2中目的,其一模块作为一个namespace让我们定义的方法名字以及常量名字和其他地方的定义不冲突,其二模块弥补了Ruby的类不能进行多重继承功能。
module Test1 def method1 end end module Test2 def method2 end end class A include Test1 include Test2 def method3 end end #实例化A类 temp = A.new #对象temp可以使用三种方法 temp.method1 temp.method2 temp.method3
0 0
- Ruby--块(Block)与模块(Module)
- Ruby模块Module
- 扇区与块(sectors,block)
- 局部变量与代码块(block)
- 扇区与块(sectors,block)
- Ruby学习笔记2(方法、块、模块)
- 代码块(block)
- ruby的类与模块(1)
- Angular2(八)--module化(核心模块与共享模块)
- Python模块(Module)
- 初探iOS中的Block(代码块与闭包)
- IOS(二)块语法block 的理解与使用
- 4、OC 块(Block)
- object-c块(block)
- C++ Block(代码块)
- 块-block(语法部分)
- ruby的Proc和代码块(Block)
- block(块),page(页),buffer cache(块缓冲)区别与联系
- MySQL 中mysql_query()来判断数据库是否连接中断(二)
- 一键退出
- C语言可变参数列表详述及实现printf函数
- (!、!!)与(空字符、undefined、0、"0")的运算
- 倒霉的猪:关于五个维度的思考
- Ruby--块(Block)与模块(Module)
- The 14th Zhejiang Provincial Collegiate Programming Contest Sponsored by TuSimple(A+B+C+D)
- Linux开发十四_ohci驱动
- ZOJ 1700 Falling Leaves 二叉搜索树+前序遍历
- js实现选项卡切换
- K Best POJ
- rem布局,页面加载时先放大一下再回复正常
- java基础总结23-java线程1
- strtok