Here is my situation. I have 2 Arrays
@names = ["Tom", "Harry", "John"]
@emails = ["tom@gmail.com", "h@gmail.com", "j@gmail.com"]
I want to combine these two into some Array/Hash called @list
so I can then iterate in my view something like this:
<% @list.each do |item| %>
<%= item.name %><br>
<%= item.email %><br>
<% end %>
I'm having trouble understanding how I can achieve this goal. Any thoughts?
Just to be different:
This is similar to what Array#zip does except that in this case there won't be any nil padding of short rows; if something is missing an exception will be raised.
Try This
You have two arrays @names = ["Tom", "Harry", "John"]
@emails = ["tom@gmail.com", "h@gmail.com", "j@gmail.com"]
@names.zip(@emails) it merge @emails to the @names associated with their index like below [["Tom", "tom@gmail.com"], ["Harry", "h@gmail.com"], ["John", "j@gmail.com"]]
Now we can convert this array into hash using Hash[@names.zip(@emails)]
This will give you a hash with name => email.
You can use
zip
to zip together the two arrays and thenmap
to createItem
objects from the name-email-pairs. Assuming you have anItem
class whoseinitialize
methods accepts a hash, the code would look like this: