rubyactionmailerpony

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 = ['example1@example.com', 'example2@example.com']
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!


Solution

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

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

    So

    ADDRESSES_BOOK[0] # returns 'example1@example.com'
    
    ADDRESSES_BOOK[1] # returns 'example2@example.com'
    

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