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


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




本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/4638698.html,如需转载请自行联系原作者


相关文章
|
2月前
|
Ruby
|
2月前
|
Ruby
|
1月前
|
数据采集 Web App开发 数据处理
Ruby网络爬虫教程:从入门到精通下载图片
Ruby网络爬虫教程:从入门到精通下载图片
|
2月前
|
JSON 数据格式 Ruby
|
2月前
|
JSON Ubuntu Linux
|
2月前
|
存储 JSON 数据格式
|
2月前
|
安全 Ruby
|
2月前
|
调度 Ruby
|
2月前
|
人工智能 BI 计算机视觉