NeoVe NeoVe - 25 days ago 4
Ruby Question

Reading CSV files with Ruby 1.9

I have a CSV file called

test.csv
like this:

id name quantity
1 warehouse_name 4


I can read the name field like this:

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


Suppose I have 300 items on the
name
field, and I just want to grab unique names, because some of them repeat.

How can I tell if they already exist?

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.