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的动态特性,很容易就达到了,使用的话:
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}
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