Ruby Merging Two Arrays into One

2019-03-11 03:32发布

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?

5条回答
forever°为你锁心
2楼-- · 2019-03-11 03:34

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.

查看更多
小情绪 Triste *
3楼-- · 2019-03-11 03:43

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)]

查看更多
在下西门庆
4楼-- · 2019-03-11 03:44
@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"
查看更多
Evening l夕情丶
5楼-- · 2019-03-11 03:46
Hash[*names.zip(emails).flatten]

This will give you a hash with name => email.

查看更多
太酷不给撩
6楼-- · 2019-03-11 03:50

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
查看更多
登录 后发表回答