Hey guys,

I'm day 3 into The Pragmatic Programmers - Seven Languages in Seven
Days, having previously done a little ruby. I'm from an Actionscript
background and finding Ruby a little challenging, so bear with me.

I've been parsing some very simple CSV, I've seen there are libraries
out there to handle this, but the book is about learning.

The book gives us some simple code and the task is to elaborate on it:

module ActsAsCsv

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def acts_as_csv
      include InstanceMethods
    end
  end

  module InstanceMethods

    def read
      @csv_contents = []
      filename = self.class.to_s.downcase + '.txt'
      file = File.new(filename)
      @headers = file.gets.chomp.split(', ')

      file.each do |row|
        @csv_contents << row.chomp.split(', ')
      end
    end

    attr_accessor :headers, :csv_contents

    def initialize
      read
    end

  end

end

class RubyCsv  # no inheritance! You can mix it in
  include ActsAsCsv
  acts_as_csv
end

m = RubyCsv.new
puts m.headers.inspect
puts m.csv_contents.inspect

The task is to create an *each* method and return a CsvRow object
instead of an array.

So I figure I need to create the object first in the file.each loop

This mess is where I got to:

file.each do |row|
        @headers.each_with_index do |head, index|
          require 'ostruct'
          rowObject = OpenStruct.new
          rowObject.#{@headers[index]} = row.chomp.split(', ')

        end
        @csv_contents << rowObject
      end

But as you can see it's a mess

I've also read some other posts around the internet and on here and
thought this might work but haven't tried it yet

file.each_with_index do |row, rowIndex|
    @headers.each_with_index do |head, headIndex|
        require 'ostruct'
        rowObject = OpenStruct.new( :#{@header[headIndex =>
row[rowIndex]}

Or something...

All help and guidance gratefully received.

Attachments:
http://www.ruby-forum.com/attachment/6164/acts_as_csv_module_original.rb


-- 
Posted via http://www.ruby-forum.com/.