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}
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}
相关文章推荐
- ruby1.8.7/rails2.3.11--启动报错"undefined method `source_index' for Gem:Module (NoMethodError)"
- Ubuntu下搭建Ruby On Rails
- 关于Ruby on rails 环境搭建的问题备忘
- Ruby第二天作业
- Ruby on Rails 和 J2EE:两个 Web 应用程序框架的比较
- Ruby安装
- perl,ruby,python 个人看法(内部讨论)
- Ruby on Rails初涉——安装
- Ruby第一天作业
- HomeBrew的安装(如何安装Ruby)
- .nil? .empty? .blank? .present? in Ruby on Rails
- ruby 资料整理
- 如何在Mac OS X上安装 Ruby运行环境
- Ruby相关图书推荐
- 安装 Ruby的三种方法
- RubyGems 镜像
- Ruby: Count unique elements and their occurences in an array
- 安装 redmine遇到的两个问题
- Codewars练习:Ruby中的ceil与floor
- ruby 安装 gem 降级