Ruby 元编程
Ruby 隨著美元在抽象的層面語言的編程支持。相當強大,假定商業(yè)模式有一個非常大的階段似性別,我相信元編程讓你節(jié)省大量的代碼。
對于一小部分,如以下。(在這里,我們只使用一個class_eval , 并且instance_eval, module_eval, Function.parameters等大量方法能夠調用)
比方 。依據(jù)業(yè)務需求。須要創(chuàng)建多個有相似方法名的類, 比方方法都命令為 include_xxx, append_xxx, delete_xxx, ?xxxs等 xxx 為詳細的業(yè)務類。
那么能夠設計例如以下一個類。 實現(xiàn)此功能。
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
執(zhí)行結果例如以下:
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
版權聲明:本文博客原創(chuàng)文章,博客,未經同意,不得轉載。
總結
- 上一篇: Python map, reduce,
- 下一篇: [Angularjs]视图和路由(三)