Creating Classes and Variables out of Text file in Ruby

Hi, I’m pretty new to Ruby and I am trying to read a text file and create a class and variables directly from it. The text file looks like this:

Video
ID : 481 (0x1E1)
Menu ID : 1 (0x1)
Format : AVC
Format/Info : Advanced Video Codec

Audio #1
ID : 482 (0x1E2)
Menu ID : 1 (0x1)
Format : AC-3
Format/Info : Audio Coding 3
Mode extension : CM (complete main)

I would like to create a class called “Video” and one called “Audio” and have all the values as variables in Ruby for each class. Any help would be much appreciated! Thanks.

Hi Demian!
You could create a couple of class files first called “Video” and “Audio,” and then iterate the text file you have with the data to create the instances for these classes (the instances should store your values).

So, there are the classes:
video.rb

Class Video 
  def initialize(data)
     @data = data
     @id = data[:id]
     @menu_id = data[:menu_id]
     @format = data[:format]
     @format_info = data[:format_info]
  end
end

audio.rb

Class Audio 
  def initialize(data)
     @data = data
     @id = data[:id]
     @menu_id = data[:menu_id]
     @format = data[:format]
     @format_info = data[:format_info]
     @mode extension = data[:mode_extension]
  end
end

I highly suggest changing the format of your data file for an easily readable format, which could be YAML or json:

media.yml

Video:
  id: 481 (0x1E1)
  menu_id: 1 (0x1)
  format: AVC
  format_info: Advanced Video Codec

Audio1:
  id: 482 (0x1E2)
  menu_id: 1 (0x1)
  format: AC-3
  format_info: Audio Coding 3
  mode_extension: CM (complete main)

Then you can iterate the values:

media_data = YAML.load_file('media.yml')

media_data.each do |key, data|
  if key == 'Video'
   @video = Video.new(data)
  else
   @audio = Audio.new(data)
  end
end

The code above could be improved and better distributed, but the idea is basically that.
Hope this helps you a little to find a solution for your issue. Have a good one!