I am implementing a data structure using Ruby and the BinData gem. I need to implement a Choice value. According to the BinData documentation, a choice can be implemented as:

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

I need to have a default option in the choice:

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

How can that be handled if type is not 0 or 1 in the above code?

有帮助吗?

解决方案 2

Well I found a work around. Anyway any other option is also most welcome.

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

其他提示

BinData 1.4.1 handles this natively with :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

you could set a default in a constructor perhaps...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top