16 csv ruby-on-rails
我正在使用ruby 1.9.2.我的csv文件如下..,
NAME, Id, No, Dept
Tom, 1, 12, CS
Hendry, 2, 35, EC
Bahamas, 3, 21, IT
Frank, 4, 61, EE
Run Code Online (Sandbox Code Playgroud)
我想打印一个特定的行('Tom').我在很多方面尝试过,但我没有找到确切的结果.最推荐的选项是"Fastercsv".但它适用于我的版本.另外,我注意到csv以列方式打印字段.如何在rails中使用csv打印整行.我的ruby代码如下
require 'csv'
csv_text = File.read('sampler.csv')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
puts "#{row[:NAME]},#{row[:Id]},#{row[:No]},#{row[:Dept]}"
end
Run Code Online (Sandbox Code Playgroud)
Rea*_*onk 20
.findcsv = CSV.read( "sampler.csv", header: true )
puts csv.find {|row| row['NAME'] == 'Tom'} #=> returns first `row` that satisfies the block.
Run Code Online (Sandbox Code Playgroud)
这是将代码保留在 CSV API 中的另一种方法。
csv_table是一个CSV::Table
row是一个CSV::Row
row_with_specified_name是一个CSV::Row。
csv_table = CSV.table("./tables/example.csv", converters: :all)
row_with_specified_name = csv_table.find do |row|
row.field(:name) == 'Bahamas'
end
p row_with_specified_name.to_csv.chomp #=> "Bahamas,3,21,IT"
Run Code Online (Sandbox Code Playgroud)
仅供参考,CSV.table只是一个捷径:
CSV.read( path, { headers: true,
converters: :numeric,
header_converters: :symbol }.merge(options) )
Run Code Online (Sandbox Code Playgroud)
根据文档。