From 49f768ec2e6cbeb82aaf541cb762193d59ab8def Mon Sep 17 00:00:00 2001 From: halida Date: Fri, 26 Sep 2014 14:10:25 +0800 Subject: [PATCH] csv use header --- ruby/csv/run.rb | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/ruby/csv/run.rb b/ruby/csv/run.rb index e7d073f..1b26b76 100644 --- a/ruby/csv/run.rb +++ b/ruby/csv/run.rb @@ -5,11 +5,24 @@ # write CSV.open(filename, "wb+") do |csv| - csv << ["row", "of", "CSV", "data"] - csv << ["another", "row"] + csv << ["ID", "name", "value"] + csv << [1, "halida", 120] + csv << [2, "James", 300] end +# read as table +c = CSV.new(File.open(filename), headers: :first_row) +# read first +row = c.readline +# read all +c.read +puts "ID: #{row['ID']}" +# return all fields +puts "first line: #{row.fields}" + +# read all CSV.foreach(filename) do |row| - puts row.to_s + row.to_s end +