Here is my situation. I have 2 Arrays
@names = ["Tom", "Harry", "John"]
@emails = ["[email protected]", "[email protected]", "[email protected]"]
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?
@names = ["Tom", "Harry", "John"]
@emails = ["[email protected]", "[email protected]", "[email protected]"]
@list = @names.zip( @emails )
#=> [["Tom", "[email protected]"], ["Harry", "[email protected]"], ["John", "[email protected]"]]
@list.each do |name,email|
# When a block is passed an array you can automatically "destructure"
# the array parts into named variables. Yay for Ruby!
p "#{name} <#{email}>"
end
#=> "Tom <[email protected]>"
#=> "Harry <[email protected]>"
#=> "John <[email protected]>"
@urls = ["yahoo.com", "ebay.com", "google.com"]
# Zipping multiple arrays together
@names.zip( @emails, @urls ).each do |name,email,url|
p "#{name} <#{email}> :: #{url}"
end
#=> "Tom <[email protected]> :: yahoo.com"
#=> "Harry <[email protected]> :: ebay.com"
#=> "John <[email protected]> :: google.com"
Just to be different:
[@names, @emails, @urls].transpose.each do |name, email, url|
# . . .
end
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With