NeoVe NeoVe - 1 year ago 71
Ruby Question

Reading CSV files with Ruby 1.9

I have a CSV file called

like this:

id name quantity
1 warehouse_name 4

I can read the name field like this:

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

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

How can I tell if they already exist?

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download