将数组的zip数组压缩到另一个数组

时间:2015-08-05 20:02:18

标签: ruby

我们说我有一个数组

Failed to publish module
   org.eclipse.core.runtime.CoreException: Module named '_auto_generated_ear_' failed to deploy. See Error Log view for more detail.
   Contains: weblogic.application.ModuleException: Failed to load webapp: 'FileTrackerWAR'
   java.lang.Exception: Exception received from deployment driver. See Error Log view for more detail.
   Caused by: weblogic.application.ModuleException: Failed to load webapp: 'FileTrackerWAR'
   Caused by: java.lang.UnsupportedClassVersionError: com/gm/gif/FileTrackerResultsServlet : Unsupported major.minor version 51.0

我想将一个数组数组压缩到它

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

以便最终结果是

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

现在我正在做的是[["a", 1, "foo"], ["b", 2, "bar"], ["c", 3, "baz"]] ,但我想知道是否有更好的方法可以做到这一点?

4 个答案:

答案 0 :(得分:11)

另一种方式是:

arr1.zip(*arr2.transpose)
# => [["a", 1, "foo"], ["b", 2, "bar"], ["c", 3, "baz"]]

答案 1 :(得分:3)

以下是另外两种(密切相关的)方式:

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

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

答案 2 :(得分:1)

arr2.each_with_index{ |el,i| el.unshift(arr1[i]) }

也许你更喜欢那样?

答案 3 :(得分:1)

如果需要将arr2的内容放在arr1的内容之前,则不能使用#transpose技巧。但是,您可以:

arr1.map.with_index { |el, i| [*arr2[i], el] }
# => [[1, "foo", "a"], [2, "bar", "b"], [3, "baz", "c"]]

具有以下特权:

  1. 不更改原始数组
  2. 让您选择订单

在性能方面,Doguita的回答似乎更好:

arr1 = %w(foo) * 10_000
arr2 = arr1.length.times.map { |i| [i, i.to_s(2)] }
Benchmark.bmbm(20) do |x|
  x.report("zip & transpose:") { arr1.zip(*arr2.transpose) }
  x.report("map & with_index:") { arr1.map.with_index { |v, i| [v, *arr2[i]] } }
end
Rehearsal --------------------------------------------------------
zip & transpose:       0.000902   0.000233   0.001135 (  0.001107)
map & with_index:      0.004206   0.002308   0.006514 (  0.006828)
----------------------------------------------- total: 0.007649sec

                           user     system      total        real
zip & transpose:       0.001474   0.000045   0.001519 (  0.001471)
map & with_index:      0.002155   0.000059   0.002214 (  0.002282)