閱讀26 返回首頁    go 阿裏雲 go 技術社區[雲棲]


為BitStruct添加list類型

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}
文章轉自莊周夢蝶  ,原文發布時間 2008-01-27

最後更新:2017-05-17 17:31:45

  上一篇:go  JRuby的性能優化(update)
  下一篇:go  Ruby處理二進製