Ruby 元编程
2015-07-11 15:12
447 查看
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
对于一小部分,如以下。(在这里,我们只使用一个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
相关文章推荐
- Ruby on Rails Tutorial 第四章 Rails背后的Ruby 之 类
- Ruby on Rails Tutorial 第四章 Rails背后的Ruby 之 其他数据类型(二)
- Ruby on Rails Tutorial 第四章 Rails背后的Ruby 之 字符串
- Ruby学习
- 如何在Mac OS X上安装 Ruby运行环境 对于新入门的开发者,如何安装 Ruby和Ruby Gems 的运行环境可能会是个问题,本页主要介绍如何用一条靠谱的路子快速安装 Ruby 开发环境。
- 如何开发一个自己的 RubyGem?
- ruby-日记
- Mac 下安装Ruby环境
- Mac 下安装Ruby环境
- 每个程序员都应该学习使用Python或Ruby
- Ruby Style Guide。
- Ruby on Rails 3 Style Guide。
- Ruby Profiler详解之stackprof
- Ruby Profiler 详解之 stackprof
- Ruby on Rails 使用mysql数据库 use local and remote mysql in development production environments in Ruby o
- 关于ActiveSupport::Concern
- 总结 | 如何测试你自己的 RubyGem
- 总结 | 如何测试你自己的 RubyGem
- 如何测试你自己的 RubyGem?
- 如何开发一个自己的 RubyGem?