编程打卡:来玩玩Ruby语言吧3!

松坂制糖厂 / 2023-04-28 / 原文

编程打卡:来玩玩Ruby语言吧3!

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

    module ClassMethods
        def act_as_csv
            include InstanceMethods
        end
    end

    module InstanceMethods

        def read
            @csv_contents = []
            filename = self.class.to_s.downcase + '.txt'
            file = File.new(filename)
            @header = 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
    include ActAsCsv
    act_as_csv
end

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