1

假设我有这两个数组数组:

a = [[1],[2],[3]]
b = [[4],[5],[6]]

有没有一个选项可以让我像这样组合它们:

a.combined_somehow(b) == [[1,4],[2,5],[3,6]]

因为我希望它防止我在内部数组中重复。我的意思是,如果是:

a = [[1],[2],[3]]
b = [[1],[5],[3]]

输出将是:[[1],[2,5],[3]]

4

4 回答 4

4
a = [[1],[2],[3]]
b = [[4],[5],[6]]

a.flatten.zip(b.flatten).map(&:uniq) # => [[1, 4], [2, 5], [3, 6]] 

b = [[1],[5],[3]]
a.flatten.zip(b.flatten).map(&:uniq) # => [[1], [2, 5], [3]] 
于 2013-11-04T22:29:39.827 回答
1
require 'pp'

a = [[1],[2],[3]]
b = [[1],[5],[3]]

def combine( a, b )
  [ a.flatten, b.flatten ].transpose.map(&:uniq)
end

pp combine( a, b )

输出

[[1], [2, 5], [3]]
于 2013-11-04T22:28:26.397 回答
1

在我看来只是感觉有点像Rubyish:

a = [[1],[2],[3]]
b = [[4],[5],[6]]

p a.zip(b).map(&:flatten) #=> [[1, 4], [2, 5], [3, 6]]

a = [[1],[2],[3]]
b = [[1],[5],[3]]

p a.zip(b).map{|x|x.flatten.uniq} #=> [[1], [2, 5], [3]]
于 2013-11-04T23:45:43.067 回答
0

我会如下:

a = [[1],[2],[3]]
b = [[4],[5],[6]]
a.map.with_index{|e,i| e | b[i]}
# => [[1, 4], [2, 5], [3, 6]]

a = [[1],[2],[3]]
b = [[4],[2],[6]]
a.map.with_index{|e,i| e | b[i]}
# => [[1, 4], [2], [3, 6]]
于 2013-11-05T03:27:12.743 回答