Ruby Merging Two Arrays into One Ruby Merging Two Arrays into One arrays arrays

Ruby Merging Two Arrays into One


@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.