1.动态方法 (send && fine_method) -- 动态派发 , 动态创建, 动态内省 缩减代码
2.0.0p247 :071 > class Computer 2.0.0p247 :072?> def initialize(computer_id, data_source) 2.0.0p247 :073?> @id = computer_id 2.0.0p247 :074?> @data_source = data_source 2.0.0p247 :075?> data_source.methods.grep(/^get_(.)_info$/) { 2.0.0p247 :076 > Computer.define_component $1 2.0.0p247 :077?> end 2.0.0p247 :078?> 2.0.0p247 :079 > def 2.0.0p247 :080 > self.define_component(name) 2.0.0p247 :081?> define_method(name) 2.0.0p247 :082?> info = @data_source.send "get_#{name}_info", @id 2.0.0p247 :083?> price = @data_source.send "get_#{name}_price", @id 2.0.0p247 :084?> result = "#{name.capitalize} : #{info} ($#{price})" 2.0.0p247 :085?> return "* {result}" if price >= 100 2.0.0p247 :086?> result 2.0.0p247 :087?> end 2.0.0p247 :088?> end
2.0.0p247 :481 > class SubClass 2.0.0p247 :482?> define_method :method_added do |name| 2.0.0p247 :483 > puts "# added a method #{name}" 2.0.0p247 :484?> end 2.0.0p247 :485?> end
2.0.0p247 :492 > SubClass.new.method_added "niaho" # added a method niaho => nil 2.0.0p247 :493 >
2.method_missing() 方法
覆写 method_missing
2.0.0p247 :107 > 'to_aaaa'.to_s =~ /^to_(.*)/; p $1 "aaaa" => "aaaa" 2.0.0p247 :108 > "aaaa".to_sym => :aaaa 2.0.0p247 :109 >
2.0.0p247 :130 > p="aasfasfs.asfsa.asf".gsub('.','_') => "aasfasfs_asfsa_asf" 2.0.0p247 :131 >
class Table def method_missing(id,*args,&block) return as($1.to_sym, *args,&block) if id.to_s =~ /^to_(.*)/ return rows_with($1.to_sym => args[0]) if id.to_s =~ /^rows_with_(.*)/ super end end
class MyOpneStruct def initialize @attributes = {} end def method_missing(name,*args) attribute = name.to_s if attribute =~ /=$/ @attributes[attribute.chop] = args[0] else @attributes[attribute] end end end icecream = MyOpneStruct.new icecream.flavor = "vanilla" icecream.flavor