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=[]
size=e.new.size
num=self.body.size/size-1
for i in 0..num
result[i]=e.new(self.body[i*size,size])
result
here
end
end利用ruby的動态特性,很容易就達到了,使用的話:
class a <bitstruct
unsigned :id,32
end
class b<bitstruct
list :alist,a
alist=[]
for i in 0..10
a=a.new
a.id=i
alist.unshift a
b=b.new
b.alist=alist
b.alist.each{|e| puts e.id}
文章轉自莊周夢蝶 ,原文釋出時間 2008-01-27