简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM