Ruby/Development/csv
Материал из Wiki.crossplatform.ru
(Различия между версиями)
Версия 17:10, 26 мая 2010
Create data for CSV file
cd=[] cd[0]=CSV::ColData.new cd[0].data="joe" cd[0].isNull=false cd[1]=CSV::ColData.new cd[1].data=27 cd[1].isNull=false cd[2]=CSV::ColData.new cd[2].data=32000 cd[2].isNull=false csv_str="" c = CSV::createLine(cd, 3, csv_str)
find the people in your database whose ages are between 20 and 40:
require "csv" people = CSV.read("text.txt") young_people = people.find_all do |p| p[3].to_i.between?(20, 40) end puts young_people.inspect //File: text.txt F,M,M,45 L,C,F,23 D,P,F,38
loading the data from a CSV-formatted file into an array is with CSV.read:
puts CSV.read("text.txt").inspect //File: text.txt F,M,M,45 L,C,F,23 D,P,F,38
Parse one CSV file line
require "csv" file_str = File.open("data.csv").read rec = []; pos=nil; i=-1 c,pos = CSV::parseLine(file_str, pos.to_i, rec[(i+=1)]=[]) until pos == 0
pick out the first person in the data called Laura:
require "csv" people = CSV.read("text.txt") laura = people.find { |person| person[0] =~ /Laura/ } puts laura.inspect //File: text.txt F,M,M,45 L,C,F,23 D,P,F,38
Read CSV file
require "csv" IO.foreach("data.csv") { |f| p CSV::parse(f.chomp) }
Reading and Searching CSV Data
require "csv" CSV.open("text.txt", "r") do |person| puts person.inspect end //File: text.txt F,M,M,45 L,C,F,23 D,P,F,38
Saving Data Back to the CSV File
require "csv" people = CSV.read("text.txt") laura = people.find { |person| person[0] =~ /Laura/ } laura[0] = "Lauren Smith" CSV.open("text.txt", "w") do |csv| people.each do |person| csv << person end end //File: text.txt F,M,M,45 L,C,F,23 D,P,F,38
Update a CSV file
require "csv" File.open("newdata.csv","w") do |file| IO.foreach("data.csv") do |line| a=CSV::parse line.chomp if a[1].to_i > 20 s=a[2].to_i a[2]=s*1.1 # 10% raise end file.puts CSV::create(a) end end
use CSV alongside the File class
require "csv" people = CSV.parse(File.read("text.txt")) puts people[0][0] puts people[1][0] puts people[2][0] //File: text.txt F,M,M,45 L,C,F,23 D,P,F,38