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