# cool dynamic method usage
class MyClass
define_method :my_method do |my_arg|
my_arg * 8
end
end
m = MyClass.new
p m.my_method 8
p m.send(:my_method, 9)# a more complicated example
puts "============== Example ==============="
# Dynamic Example
# Dynamic Model
class MOUSE
attr_accessor :price, :info, :c_id
def initialize price, info, c_id
@price, @info, @c_id = price, info, c_id
end
end
class CPU
attr_accessor :price, :info, :c_id
def initialize price, info, c_id
@price, @info, @c_id = price, info, c_id
end
end
class KEYBOARD
attr_reader :price, :info, :c_id
def initialize price, info, c_id
@price, @info, @c_id = price, info, c_id
end
end
# Dynamic Method DS
class DS
def initialize
@data = []
end
def addCom *component
component.each{|c| @data << c }
end
def count
@data.count
end
class << DS
def define_get_method *component_name
component_name.each do |each|
%w-_info _price-.each do |content|
define_method ("get_" + each.to_s + content).to_sym do |c_id|
comArray = @data.select{|x| x.c_id == c_id}
com = comArray.select{|x| x.is_a? eval(each.to_s.upcase)}
com[0].send(content[1..-1])
end
end
end
end
end
define_get_method :mouse, :keyboard, :cpu
end
#data prepare
k1 = KEYBOARD.new 10, "keyboard_1", 1
k2 = KEYBOARD.new 40, "keyboard_1", 2
k3 = KEYBOARD.new 100, "keyboard_1", 3
c1 = CPU.new 200, "cpu_1", 1
m1 = MOUSE.new 1000, "apple Inc", 1
ds = DS.new
ds.addCom k1, k2, k3, c1, m1
p ds.count
p (ds.get_mouse_info 1), (ds.get_mouse_price 1)
p ds.get_keyboard_info 1
p ds.get_cpu_info 1
# more about dynamic method
class Computer
def initialize computer_id, data_source
@id = computer_id
@data_source = data_source
data_source.methods.grep(/^get_(.*)_info$/){Computer.define_component $1}
end
def self.define_component name
define_method(name){
info = @data_source.send "get_#{name}_info", @id
price = @data_source.send "get_#{name}_price", @id
result = "#{name.capitalize}: #{info} $#{price}"
return "**#{result}" if price > 500
result
}
end
end
puts "-----------------final invoke..-----------------"
c = Computer.new 1, ds
p c.keyboard
p c.mouse
分享到:
相关推荐
- **与静态类型的交互**:通过使用`dynamic`关键字和`System.Dynamic`命名空间中的类型,可以方便地在C#中调用动态语言的对象和方法。 ### 总结 通过对《Metaprogramming in .NET》的内容总结,我们可以看到.NET...
1. 一般规定(General) - 标准的范围(Scope)涵盖了C++语言的定义,以及在C++中可以使用的所有特性。 - 引用标准(Normative references)列出了本标准依赖的其他标准文档。 - 术语和定义(Terms and ...
1. 动态类型:Python是一种动态类型的语言,这意味着开发者无需在声明变量时指定其数据类型。变量的类型可以在程序运行过程中根据赋值自动改变,如: ```python x = 5 # x 是整型 x = "Hello" # 现在 x 是字符串 ...
method_missing是Ruby元编程(metaprogramming)常用的手法。基本思想是通过实现调用不存在的方法,以便进行回调。典型的例子是:ActiveRecord的动态查找(dynamic finder)。例如:我们有email属性那么就可以调用...
5. 原型模式(Singleton):Ruby没有内置的单例模式,但可以通过模块(Module)和元编程(Metaprogramming)实现。单例类确保一个类只有一个实例。 6. 动态方法(Dynamic Methods):Ruby允许在运行时创建和修改...
1 Scope 1 2 Normative references 2 3 Terms and definitions 3 4 General principles 7 4.1 Implementation compliance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.2 Structure ...