您的位置:首页 > 编程语言 > Ruby

Ruby第三天作业

2015-08-27 11:45 381 查看
参考网上例子:

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}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: