Sciguy77
Sciguy77

Reputation: 349

For loop through string array with array.each do not working?

I'm working on a basic contact form as part of learning Ruby where there are a string of email addresses in an array and the message in a contact form is sent to each one through Rails Pony.

ADDRESSES_BOOK = ['[email protected]', '[email protected]']
def deliver
return false unless valid?
ADDRESSES_BOOK.each do |address|
  Pony.mail({
    :to => ADDRESSES_BOOK[address],
    :from => %("#{name}" <#{email}>),
    :reply_to => email,
    :subject => subject,
    :body => contactFormMessage,
  })
end
end

I'm doing something wrong with the loop, as it throws the error "no implicit conversion of String into Integer."

What am I doing wrong here?

Thanks!

Upvotes: 0

Views: 939

Answers (2)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

try this

.....
    :to => address,
    :from => %("#{name}" <#{email}>),
    :reply_to => email,
    :subject => subject,
    :body => contactFormMessage,
.....

Upvotes: 0

Sully
Sully

Reputation: 14943

ADDRESSES_BOOK.each do |address|
  Pony.mail({
    :to => address
    #...
  })
end

When you do ADDRESSES_BOOK[address] is like saying ADDRESSES_BOOK['[email protected]'] which is trying to access the value of the array at index '[email protected]', but array indexes are integers and start from 0.

So

ADDRESSES_BOOK[0] # returns '[email protected]'

ADDRESSES_BOOK[1] # returns '[email protected]'

The .each will iterate over each element in the array and put it address

Upvotes: 1

Related Questions