1

Suppose I have two different arrays.

Emails = ["[email protected]", "[email protected]", "[email protected]"]

Names = ["Name Surname", "Name1, Surname1", "Name2, Surname2"]

And I have a mysql-table called Contacts, which I want to insert each of the values into rows called Emails and Names. Each name and email should be inserted at their according indexes. So Emails[0] should be inserted along with Names[0], Emails[1] with Names[1] etc.

If there was only one array. I could do something like

sql = "INSERT INTO Contacts (email)
VALUES
('#{email}')

Emails.each do |email|
email = email.sql
end

but now I have two arrays and I need to put them so that each email is associated according to the correct name. How do I do this?

2 Answers 2

1

Use zip:

 con.prepare "INSERT INTO Contacts(email, name) VALUES(?, ?)"
 Emails.zip(Names).each do |email,name|
   #insert into db
   con.execute(email,name) #assuming **con** is your connection object
 end
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Didn't know about zip.
1

You could do something like this if you really want to iterate:

Email.zip(Names).each do |email, name|
  sql = "INSERT INTO Contacts (email, name) VALUES ('#{email}', '#{name)')"
end

alternatively, you can probably bulk insert using

sql = "INSERT INTO Contacts (email, name) VALUES (" + 
      Emails.zip(Names).map { |e, n|  "('#{e}', '#{n}')" }.join(",") + ")"

Looks kind of ugly, but you get the idea

Comments

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.