Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a specific row in csv

I'm using ruby 1.9.2. My csv file as follows..,

NAME,    Id,   No,  Dept
Tom,     1,    12,   CS
Hendry,  2,    35,   EC
Bahamas, 3,    21,   IT
Frank,   4,    61,   EE

I want to print an specific row say ('Tom'). I tried out in many ways, but I didn't find the exact result. The most recommended options is "Fastercsv". But it is applicable for my version. Also, I noticed that csv print the field as column wise. How to print an entire row using csv in rails. My ruby code is as follows

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

2 Answers

Use .find

csv = CSV.read('sampler.csv', headers: true)

puts csv.find {|row| row['NAME'] == 'Tom'} #=> returns first `row` that satisfies the block.
like image 87
Reactormonk Avatar answered Sep 10 '25 11:09

Reactormonk


Here's another approach that keeps the code within the CSV API.

csv_table is a CSV::Table
row is a CSV::Row
row_with_specified_name is a 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"

FYI, CSV.table is just a shortcut for:

CSV.read( path, { headers:           true,
                  converters:        :numeric,
                  header_converters: :symbol }.merge(options) )

As per the docs.

like image 42
sealocal Avatar answered Sep 10 '25 13:09

sealocal