PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 27, 2022

[FIXED] How to find a specific row in csv

 August 27, 2022     csv, ruby-on-rails     No comments   

Issue

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

Solution

Use .find

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

puts csv.find {|row| row['NAME'] == 'Tom'} #=> returns first `row` that satisfies the block.


Answered By - Reactormonk
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing