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?
Another way is:
arr1.zip(*arr2.transpose)
# => [["a", 1, "foo"], ["b", 2, "bar"], ["c", 3, "baz"]]
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"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With