zoukankan      html  css  js  c++  java
  • Ruby 元编程

    Ruby 随着美元在抽象的层面语言的编程支持。相当强大,假定商业模式有一个非常大的阶段似性别,我相信元编程让你节省大量的代码。

    对于一小部分,如以下。(在这里,我们只使用一个class_eval , 并且instance_eval, module_eval, Function.parameters等大量方法能够调用)

    比方 。依据业务需求。须要创建多个有相似方法名的类, 比方方法都命令为 include_xxx, append_xxx, delete_xxx,  xxxs等 xxx 为详细的业务类。

    那么能够设计例如以下一个类。 实现此功能。

    module Factory
        def  self.build_class(classname, cls_type)
            sub_clss = cls_type.to_s.downcase
            new_cls.class_eval <<-CLASSDEF
                def initialize
                    @container = []
                end

                def append_#{sub_clss}(key)
                    @container << key
                end

                def delete_#{sub_clss}(key)
                    @container.delete_if{|e| e == key}
                end

                def include_#{sub_clss}?(key)
                    @container.find {|e| e == key} ? true : false
                end
                def traverse

                    puts "notice container elements as follows"
                    @container.each {|e| puts e}
                end
            CLASSDEF
            new_cls
        end
    end

    执行结果例如以下:

    c1 = (Factory.build_class "C1", String)
    n = c1.new
    n.append_string("abc") 
    puts n.traverse
    puts ">>>>", n.include_string?

    ("abc")
    puts ">>>.",n.include_string?("123")
    n.delete_string("abc")
    puts n.traverse


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    对于JavaScript中this关键字的理解
    使用DOM对表格进行增删
    sql server 存储过程
    sql sever 基础 练习题
    sql sever 基础 建表
    第十章 嵌入式的Linux调试技术
    第九章 硬件抽象层 HAL
    第八章 蜂鸣器驱动
    LED:控制发光二极管
    第一个Linux驱动程序:统计单词个数
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4638698.html
Copyright © 2011-2022 走看看