莊周夢蝶

          生活、程序、未來
             :: 首頁 ::  ::  :: 聚合  :: 管理

          為BitStruct添加list類型

          Posted on 2008-01-27 15:53 dennis 閱讀(365) 評論(0)  編輯  收藏 所屬分類: 動態語言
          class BitStruct
            
          def self.list(name,element)
              module_eval 
          <<-HERE
                rest :body
                
          def #{name.to_s}=(elist)
                   e=Object.const_get(:#{element})
                   if elist.respond_to? :each and elist.respond_to? :[] and elist[0].is_a? e
                      elist.each{ 
          |value| self.body+=value}
                   elsif elist.is_a? e
                      self.body
          =elist
                   
          else
                      
          raise ArgumentError,elist.to_s<<" is not a #{element}",caller
                   end
                end
                
          def #{name.to_s}
                   result=[]
                   e
          =Object.const_get(:#{element})
                   size=e.new.size
                   num
          =self.body.size/size-1
                   
          for i in 0..num
                      result[i]
          =e.new(self.body[i*size,size])
                   end
                   result
                end
              HERE
            end
          end
          利用Ruby的動態特性,很容易就達到了,使用的話:

          class A <BitStruct
             unsigned :id,
          32
          end
          class B<BitStruct
             list :aList,A
          end
          alist
          =[]
          for i in 0..10
            a
          =A.new
            a.id
          =i
            alist.unshift a
          end
          b
          =B.new
          b.aList
          =alist
          b.aList.each{
          |e| puts e.id}

          主站蜘蛛池模板: 盖州市| 弥勒县| 凉山| 通河县| 正蓝旗| 五莲县| 商都县| 牙克石市| 饶平县| 墨竹工卡县| 长岭县| 铜川市| 崇文区| 肇源县| 松江区| 武穴市| 于都县| 睢宁县| 图们市| 富裕县| 昌平区| 茂名市| 余干县| 苗栗县| 南雄市| 延吉市| 图片| 都江堰市| 济宁市| 海晏县| 开原市| 丰都县| 襄汾县| 大英县| 丰原市| 手机| 五常市| 奉贤区| 宜城市| 上蔡县| 九龙县|