NeoVe NeoVe - 11 months ago 48
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
I can read the name field like this:

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

Now, suppose I have 300 items on
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 Source

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.