为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
目录
相关文章
|
7月前
|
存储 NoSQL Redis
Redis之List类型解读
Redis之List类型解读
|
4月前
|
Java 程序员
Java集合框架:List、Set、Map类型及泛型详解
Java集合框架:List、Set、Map类型及泛型详解
|
3月前
|
网络协议 API 开发者
Python 3.9 性能优化:更快的 list()、dict() 和 range() 等内置类型
Python 3.9 性能优化:更快的 list()、dict() 和 range() 等内置类型
14 1
|
9月前
|
Java
Java——把list转为List<clazz>类型
Java——把list转为List<clazz>类型
|
4月前
PyQt5 用信号槽传递list, dict可变类型
PyQt5 用信号槽传递list, dict可变类型
17 0
|
5月前
|
SQL IDE Java
MyBatis【问题 01】mapper传入array\collection\list类型的参数时报BindingException:Parameter ‘xx‘ not found问题复现及解决
MyBatis【问题 01】mapper传入array\collection\list类型的参数时报BindingException:Parameter ‘xx‘ not found问题复现及解决
63 0
|
5月前
|
XML Java 数据格式
spring怎么去引用/注入集合/数组类型和 怎么通过 util 名称空间创建 list以及 怎么去通过级联属性赋值
spring怎么去引用/注入集合/数组类型和 怎么通过 util 名称空间创建 list以及 怎么去通过级联属性赋值
34 0
|
9月前
把list转为List<clazz>类型,并把字典项转为字典值
把list转为List<clazz>类型,并把字典项转为字典值
|
9月前
|
存储 NoSQL Redis
Redis 中 List(列表)类型的命令及详解
Redis 中 List(列表)类型的命令及详解
109 0
|
10月前
|
算法 IDE 开发工具
【Python语法】类型提示(self, nums: List[int]) -> List[int],报错NameError: name ‘List‘ is not defined解决
【Python语法】类型提示(self, nums: List[int]) -> List[int],报错NameError: name ‘List‘ is not defined解决