Michelle Glauser
Michelle Glauser

Reputation: 1097

How do I make an array of arrays out of a CSV?

I have a CSV file that looks like this:

Jenny, [email protected] ,
Ricky, [email protected] ,
Josefina [email protected] ,

I'm trying to get this output:

users_array = [
['Jenny', '[email protected]'], ['Ricky', '[email protected]'], ['Josefina', '[email protected]']
]

I've tried this:

users_array = Array.new

file = File.new('csv_file.csv', 'r') 
file.each_line("\n") do |row| 
    puts row + "\n" 
    columns = row.split(",") 
    users_array.push columns 
    puts users_array
end 

Unfortunately, in Terminal, this returns:

Jenny
[email protected]
Ricky
[email protected]
Josefina
[email protected]

Which I don't think will work for this:

users_array.each_with_index do |user|
    add_page.form_with(:id => 'new_user') do |f|
      f.field_with(:id => "user_email").value = user[0]
      f.field_with(:id => "user_name").value = user[1]
    end.click_button
end

What do I need to change? Or is there a better way to solve this problem?

Upvotes: 1

Views: 72

Answers (2)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

Assuming that your CSV file actually has a comma between the name and email address on the third line:

require 'csv'

users_array = []
CSV.foreach('csv_file.csv') do |row|
  users_array.push row.delete_if(&:nil?).map(&:strip)
end

users_array
# => [["Jenny", "[email protected]"],
#     ["Ricky", "[email protected]"],
#     ["Josefina", "[email protected]"]]

There may be a simpler way, but what I'm doing there is discarding the nil field created by the trailing comma and stripping the spaces around the email addresses.

Upvotes: 0

Zach Kemp
Zach Kemp

Reputation: 11904

Ruby's standard library has a CSV class with a similar api to File but contains a number of useful methods for working with tabular data. To get the output you want, all you need to do is this:

require 'csv'
users_array = CSV.read('csv_file.csv')

PS - I think you are getting the output you expected with your file parsing as well, but maybe you're thrown off by how it is printing to the terminal. puts behaves differently with arrays, printing each member object on a new line instead of as a single array. If you want to view it as an array, use puts my_array.inspect.

Upvotes: 1

Related Questions