Ruby - Grouping data from CSV file by a column

I have a CSV file that looks like this:

+---------+----------+
|  Name   |  Stream  |
+---------+----------+
| Jacob   | Computer |
| Ryan    | Arts     |
| Bob     | Computer |
| Charlie | Science  |
| Grace   | Arts     |
+---------+----------+

I need to read this CSV file and group the students based on their stream. The output should be like this:

Computer
----------
Jacob
Bob

Arts
------
Ryan
Grace

Science
--------
Charlie

I tried to use group_by, but was not sure how and where to use it. Any help would be much appreciated.

1 answer

  • answered 2018-11-08 08:48 VAD

    I assume you have csv file with the following content:

    Name,Stream
    Jacob,Computer
    Ryan,Arts
    Bob,Computer
    Charlie,Science
    Grace,Arts
    

    You can use something like this

    require 'csv'    
    
    result = {}
    file = File.read('path_to_your_file')
    csv = CSV.parse(file, headers: true)
    csv.each do |row|
      if result[row[1]]
        result[row[1]].push row[0]
      else
        result[row[1]] = [row[0]]
      end
    end
    

    You'll get result variable containing a hash where every stream will be associated with an array of names