Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip array of arrays to another array

Tags:

ruby

Let's say I have an array

arr1 = ["a", "b", "c"]

and I want to zip an array of arrays to it

arr2 = [[1, "foo"], [2, "bar"], [3, "baz"]]

so that the end result is

[["a", 1, "foo"], ["b", 2, "bar"], ["c", 3, "baz"]]

Right now what I'm doing is arr1.zip(arr2).map!(&:flatten), but I'm wondering if there's a better way to do this?

like image 940
Patosai Avatar asked Aug 05 '15 20:08

Patosai


2 Answers

Another way is:

arr1.zip(*arr2.transpose)
# => [["a", 1, "foo"], ["b", 2, "bar"], ["c", 3, "baz"]]
like image 88
Doguita Avatar answered Nov 15 '22 12:11

Doguita


Here are two other (closely-related) ways:

enum = arr1.to_enum
arr2.map { |a| [enum.next].concat(a) }
  #=> [["a", 1, "foo"], ["b", 2, "bar"], ["c", 3, "baz"]] 

or

arr1_cpy = arr1.dup
arr2.map { |a| [arr1_cpy.shift].concat(a) }
  #=> [["a", 1, "foo"], ["b", 2, "bar"], ["c", 3, "baz"]] 
like image 35
Cary Swoveland Avatar answered Nov 15 '22 12:11

Cary Swoveland