莊周夢蝶

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

          為BitStruct添加list類型

          Posted on 2008-01-27 15:53 dennis 閱讀(365) 評論(0)  編輯  收藏 所屬分類: 動態(tài)語言
          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的動態(tài)特性,很容易就達到了,使用的話:

          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}

          主站蜘蛛池模板: 田阳县| 通江县| 绥中县| 弥渡县| 九龙县| 常州市| 治县。| 禄劝| 交口县| 高碑店市| 潮安县| 水城县| 城市| 呼和浩特市| 乌什县| 屏东市| 巴彦淖尔市| 定陶县| 吕梁市| 清水县| 册亨县| 武平县| 克什克腾旗| 体育| 澄城县| 潢川县| 图们市| 通渭县| 修水县| 纳雍县| 集安市| 双峰县| 平谷区| 盘山县| 绥宁县| 屯昌县| 岐山县| 临城县| 泉州市| 嘉兴市| 武平县|