How do easily filter CSV data in Ruby
Asked Answered
L

1

6

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 }
Latterll answered 3/11, 2016 at 11:53 Comment(0)
N
10

I don't think you need a gem here:

csv.select { |row| row['GENDER'] == 'MALE' }
csv.select { |row| row['GENDER'] == 'MALE' || row['SALARY'] >= 10000 }
Nicolais answered 3/11, 2016 at 11:55 Comment(5)
Thanks Andrey. I need to process this csv for multiple data queries hence I am looking for a solution out of the box without having to write what you suggested above.Latterll
@Latterll What do you mean out of the box? Is 2 lines of code not out of the box enough for you? :)Nicolais
Andrey, what I mean is some gem/helper that allows me to use the syntax I specified. It's 2 lines of code but I need to filter data multiple times and using various filter criteria.Latterll
@Latterll I agree with Andrey, you have in any case to specify your conditions and select syntax is not so more verbose than the one you provide. I mean, no need for a gem.Deflagrate
@Latterll there is no such gem because it does not even make sense to create one with such functionality. Think of it - you are looking for some sort of activerecord syntax while saying you want a non-Rails solution. If you want non-Rails solution - use Ruby, it is there for you with simple ready-to-go methods. Your needs are elementary and I do not see how would any gem simplify itNicolais

© 2022 - 2024 — McMap. All rights reserved.