1

So I am trying to parse a list of emails separated by a comma and inputted in a form using the built-in CSV library in rails 3.

Here is the code:

@variable = params[:body]
@csv = CSV.parse(@variable, :col_sep => ",")
  @csv.each do |row|
    user = User.where(:email => row)

However, the output is something like this:


- - [email protected]
  - ! ' [email protected]'

Therefore, each row in the @csv that I am trying to go over is an entire list of emails. How can I separate them? Thanks!

1 Answer 1

1

CSV::parse returns an array of arrays if you don't pass a block as an argument. So when you enumerate @csv using #each, the argument row will be an array of strings. Not a single string as your code suggests.

If the email address is the first column of each row in your CSV file, then you would replace

User.where(:email => row)

with

User.where(:email => row[0])

It's not exactly clear what the format of your CSV file is though. If you have multiple email addresses per row, or have the email address in a different column, you'll have to revise the code accordingly.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply. So I am receiving a user input of CSV such as ([email protected], [email protected], [email protected]) I want to send an email to each user so I need to separate the values. I tried the row[0], but it only gave me the first email and it stopped looping...
OK, sounds like you have one row with many comma separated values. In that case, using the CSV module would work but is overkill. You could just use String#split to turn params[:body] into an Array of strings, instead of calling CSV#parse and each. Or you could stick with what you've done. Either way, once you've got an array of strings (which is what row is currently), then you can either use the whole array to fetch a set of users User.where(:email => row) or you can iterate through the array an element at a time using each to process each element singly.
In case you didn't know, CSV, String, Array and other standard classes are documented at wwww.ruby-doc.org
You're right. Split works much better for my case. Thanks man!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.