天天看点

为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=[]

         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