Ruby Merging Two Arrays into One
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 though开发者_如何学JAVAts?
@names = ["Tom", "Harry", "John"]
@emails = ["tom@gmail.com", "h@gmail.com", "j@gmail.com"]
@list = @names.zip( @emails )
#=> [["Tom", "tom@gmail.com"], ["Harry", "h@gmail.com"], ["John", "j@gmail.com"]]
@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 <tom@gmail.com>"
#=> "Harry <h@gmail.com>"
#=> "John <j@gmail.com>"
@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 <tom@gmail.com> :: yahoo.com"
#=> "Harry <h@gmail.com> :: ebay.com"
#=> "John <j@gmail.com> :: 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.
Hash[*names.zip(emails).flatten]
This will give you a hash with name => email.
You can use zip
to zip together the two arrays and then map
to create Item
objects from the name-email-pairs. Assuming you have an Item
class whose initialize
methods accepts a hash, the code would look like this:
@list = @names.zip(@emails).map do |name, email|
Item.new(:name => name, :email => email)
end
Try This
Hash[@names.zip(@emails)]
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)]
精彩评论