使用Packed Arrays进行Woking,访问数据

时间:2014-01-29 02:17:22

标签: ruby-on-rails ruby arrays pack

我正在处理一个大型图像阵列,所以我打包了它。为了访问阵列中的像素,我实现了两种方法。

def get_p(a)
  data=a.unpack('S9s')
end
def put_p(array,index_a,value)
  index=index_a[0]
  k=array.unpack('S9s')
  k[index]=value
  k.pack('S9s')
end

它有效,但我想知道是否有一种更优雅的方式来做到这一点。使我的代码看起来与我的标准数组函数不同。

If get_p(image_data[i][j+1])[BLOB]==0

VS

if image_data[i][j+1][BLOB]==0

另外,不知道是否有人关心,但解压缩似乎没有记录在任何地方,我很幸运能在这里找到参考,但是花了一些时间。

1 个答案:

答案 0 :(得分:2)

你可以喜欢这样的课程:

class PackedArray

  def initialize(array)
    @packed_array = array.pack('S9s')
  end

  def [](key)
    data = @packed_array.unpack('S9s')
    data[key]
  end

  def []=(key, val)
    k = @packed_array.unpack('S9s')
    k[key]=val
    @packed_array = k.pack('S9s')
  end
end

然后,用您的image_data[i][j]填充此类的实例。 E.g。

for i in [0..image_data.size]
  for j in [0..image_data[i].size]
    image_data[i][j] = new PackedArray(image_data[i][j])  
  end
end

最后你可以简单地使用:

if image_data[i][j+1][BLOB] == 0

无需手动打包/拆包。