Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do easily filter CSV data in Ruby

I am dealing with a CSV file(approx 500 lines). Is there a way to select data from this file with filters. I know I can do this in ruby by parsing the csv and using select/find methods But I am looking for a simpler syntax. I don't want to write methods to process each of the below queries. Any gem that would allow me do these queries? I am looking for a non-Rails solution as I am writing a plain ruby script.

e.g.

csv.find_rows(where: {'GENDER' => 'MALE'}.count

or

csv.find_rows(where: {'GENDER' => 'MALE', 'SALARY' >= 10000 }
like image 835
Rahul Avatar asked Nov 03 '16 11:11

Rahul


1 Answers

I don't think you need a gem here:

csv.select { |row| row['GENDER'] == 'MALE' }
csv.select { |row| row['GENDER'] == 'MALE' || row['SALARY'] >= 10000 }
like image 97
Andrey Deineko Avatar answered Oct 03 '22 23:10

Andrey Deineko