Ruby 元编程 方法

178 篇文章 0 订阅


1.动态方法 (send && fine_method) --  动态派发 , 动态创建,  动态内省 缩减代码

  1. 2.0.0p247 :071 >   class Computer  
  2. 2.0.0p247 :072?>    def initialize(computer_id, data_source)  
  3. 2.0.0p247 :073?>     @id = computer_id  
  4. 2.0.0p247 :074?>     @data_source = data_source  
  5. 2.0.0p247 :075?>     data_source.methods.grep(/^get_(.)_info$/) {  
  6. 2.0.0p247 :076 >         Computer.define_component $1  
  7. 2.0.0p247 :077?>       end  
  8. 2.0.0p247 :078?>       
  9. 2.0.0p247 :079 >       def  
  10. 2.0.0p247 :080 >         self.define_component(name)  
  11. 2.0.0p247 :081?>       define_method(name)  
  12. 2.0.0p247 :082?>        info = @data_source.send "get_#{name}_info"@id  
  13. 2.0.0p247 :083?>        price = @data_source.send "get_#{name}_price"@id  
  14. 2.0.0p247 :084?>       result = "#{name.capitalize} : #{info} ($#{price})"  
  15. 2.0.0p247 :085?>       return "* {result}" if price >= 100  
  16. 2.0.0p247 :086?>       result  
  17. 2.0.0p247 :087?>       end  
  18. 2.0.0p247 :088?>     end  

  1. 2.0.0p247 :481 >   class SubClass  
  2. 2.0.0p247 :482?>    define_method :method_added do |name|  
  3. 2.0.0p247 :483 >        puts "# added a method #{name}"  
  4. 2.0.0p247 :484?>     end  
  5. 2.0.0p247 :485?>   end  
  1. 2.0.0p247 :492 > SubClass.new.method_added "niaho"  
  2. # added a method niaho  
  3.  => nil   
  4. 2.0.0p247 :493 >   


2.method_missing() 方法

覆写 method_missing

  1. 2.0.0p247 :107 > 'to_aaaa'.to_s =~ /^to_(.*)/; p $1  
  2. "aaaa"  
  3.  => "aaaa"   
  4. 2.0.0p247 :108 > "aaaa".to_sym  
  5.  => :aaaa   
  6. 2.0.0p247 :109 >  
  1. 2.0.0p247 :130 > p="aasfasfs.asfsa.asf".gsub('.','_')  
  2.  => "aasfasfs_asfsa_asf"   
  3. 2.0.0p247 :131 >    


幽灵方法
  1. class Table  
  2.   def method_missing(id,*args,&block)  
  3.     return as($1.to_sym, *args,&block) if id.to_s =~ /^to_(.*)/  
  4.     return rows_with($1.to_sym => args[0]) if id.to_s =~ /^rows_with_(.*)/  
  5.     super    
  6.   end  
  7. end  

  1. class MyOpneStruct  
  2.   def initialize  
  3.     @attributes = {}  
  4.   end  
  5.   
  6.   def method_missing(name,*args)  
  7.     attribute = name.to_s  
  8.     if attribute =~ /=$/  
  9.       @attributes[attribute.chop] = args[0]  
  10.     else  
  11.       @attributes[attribute]  
  12.     end  
  13.   end  
  14. end  
  15.   
  16. icecream = MyOpneStruct.new  
  17. icecream.flavor = "vanilla"  
  18. icecream.flavor 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值