假设我有这两个数组数组:
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]]
假设我有这两个数组数组:
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]]
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]]
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]]
在我看来只是感觉有点像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]]
我会如下:
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]]