参考网上例子:
class CsvRow
attr_accessor :row, :headers
def initialize(row, headers)
@headers = {}
(0...headers.count).each {|i| @headers[headers[i]] = i} # 保存列数组
@row = row
end
def method_missing(name, *args)
@row[@headers[name.to_s]]<span style="white-space:pre"> </span># 直接调用列名方法<pre name="code" class="ruby">initialize
endendmodule ActsAsCsv def self.included(base) puts base base.extend ClassMethods end def each @csv_contents.each {|row| yield row}
# 覆盖each,调用传入函数,执行打印method_missing end module ClassMethods def acts_as_csv include InstanceMethods # 包含实例方法 end end module InstanceMethods def read @csv_contents = [] file = File.new(self.class.to_s.downcase + '.txt') @headers = file.gets.chomp.split(',') file.each do |row| @csv_contents << CsvRow.new(row.chomp.split(","), @headers)
# 放入数组 end end attr_accessor :headers, :csv_contents def initialize read
#
.new
初始化调用read
end endendclass RubyCsv include ActsAsCsv acts_as_csvendcsv = RubyCsv.newcsv.each {|row| puts row.one}