Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Merging Two Arrays into One

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?

like image 213
lou1221 Avatar asked Sep 11 '25 04:09

lou1221


2 Answers

@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"
like image 123
Phrogz Avatar answered Sep 12 '25 20:09

Phrogz


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.

like image 21
DigitalRoss Avatar answered Sep 12 '25 18:09

DigitalRoss