感觉这个有点新意。
def data_class(fields)
names = fields.keys
pattern = fields.values.join
Class.new do
attr_reader :values
define_method :initialize do |byte_string|
@values = byte_string.unpack(pattern)
end
names.each_with_index do |name, i|
define_method name do
values[i]
end
end
end
end
RGBColorData = data_class(red: "C", green: "C", blue: "C")
binary = [255, 128, 192].pack("CCC")
color = RGBColorData.new(binary)
color.red #=> 255
color.green #=> 128
color.blue #=> 192