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 }
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Rahul
  • 321
  • 2
  • 14

1 Answers1

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 }
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • 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. – Rahul Nov 03 '16 at 11:58
  • 4
    @Rahul What do you mean `out of the box?` Is 2 lines of code not `out of the box` enough for you? :) – Andrey Deineko Nov 03 '16 at 11:59
  • 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. – Rahul Nov 03 '16 at 12:03
  • 4
    @Rahul 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. – Ursus Nov 03 '16 at 12:05
  • 4
    @Rahul 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 it – Andrey Deineko Nov 03 '16 at 12:05