Search code examples
rubybinary-databindata

Using Ruby BinData gem to read choices


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?


Solution

  • 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