使用Ruby BinData gem来读取选择

时间:2011-06-11 08:21:57

标签: ruby binary-data choice bindata

我正在使用Ruby和BinData gem实现数据结构。我需要实现Choice值。根据BinData文档,选择可以实现为:

class MyData < BinData::Record
  uint8  :type
  choice :data, :selection => :type do
    type key #option 1
    type key #option 2
  end
end

我需要在选择中使用默认选项:

class MyRecord < BinData::Record
    uint8 :type
    choice :mydata, :selection => :type do
            uint32 0
            uint16 1
    end
end

如果上述代码中type不是01,该如何处理?

3 个答案:

答案 0 :(得分:5)

BinData 1.4.1本地处理:default

class MyRecord < BinData::Record
  uint8 :data_type
  choice :mydata, :selection => :data_type do
    uint32 1
    uint16 2
    string :default, :read_length => 4
  end
end

答案 1 :(得分:2)

我找到了解决方法。无论如何,任何其他选择也是最受欢迎的。

class MyRecord < BinData::Record
    uint8 :data_type
    choice :mydata, :selection => :get_choice do
            uint32 1
            uint16 2
            string 255, :read_length => 4
    end

    def get_choice
            choices = [1, 2]
            if choices.include? data_type
                    return data_type
            else
                    return 255
            end
    end
end

答案 2 :(得分:-1)

你可以在构造函数中设置默认值......