class ImageString attr_reader :columns, :rows def initialize(filename) File.open(filename, "rb") do |file| (columns_str, rows_str) = file.gets.split(" ") @columns = columns_str.to_i @rows = rows_str.to_i @image_string = file.read end end def pixel_at(row, column) location = column + (row * @columns) if location < 0 or location >= @image_string.length return nil end single = @image_string[location, 1] return (single.unpack("C"))[0] end def set_pixel(row, column, value) # TODO exception - bad position and bad value location = column + (row * @columns) # usage of pack here is to avoid differences in string[x] behavior in 1.8 and 1.9 raw_value = [value].pack("C") @image_string[location] = raw_value end def dump_to_file(filename) File.open(filename, "wb") do |out| out.puts(@columns.to_s + " " + @rows.to_s) out.puts(@image_string) end end end