NeoVe NeoVe - 28 days ago 6
Ruby Question

Reading csv's parsing with ruby 1.9

I'm fairly new to Ruby, let's say I have a csv like this:

id name quantity
1 warehouse_name 4


This file is called
test.csv
I can read the name field like this:

require 'csv'
csv = CSV.read('test.csv', :headers=>true)
p csv['name']


Now, suppose I have 300 items on
name
field, and I just want to grab unique names, because some of them repeat, how can I discriminate if they already exist?

Thanks in advance

Answer

The results of csv['name'] will be an array of strings, which you can treat like any other array of strings.

>> array = csv['name']
=> ["Mark", "Betty", "Mark", "Jane", "Fred", "Jane"]
>> array.uniq
=> ["Mark", "Betty", "Jane", "Fred"]

Refer to the docs for Array and Enumerable for much more information.