如何在Ruby中组合这两个数组数组

时间:2022-09-06 15:40:40

I have two arrays that have the same length and the same format.I am looking for the shortest way to do something like this:

我有两个具有相同长度和相同格式的数组。我正在寻找最简单的方法来做这样的事情:

[[:todo],[],['text']].some_operation([[],[:low],[]])
->
[[:todo],[:low],['text']]

as I want the duplicates to be removed:

因为我想要删除重复项:

[[:todo],[],['text']].some_operation([[:todo],[:low],['text','more']])
->
[[:todo],[:low],['text','more']]

3 个解决方案

#1


1  

If you have the values in a and b, then

如果你有a和b中的值,那么

a.zip(b).map { |aa, bb| (aa + bb).uniq }

If you really want to put it onto the Array class, you can either monkey-patch it (not really recommended, especially for something this specific), or refine it (new, won't work in older versions).

如果你真的想把它放到Array类上,你可以对它进行修补(不是真的推荐,特别是对于这个特定的东西),或者改进它(新的,在旧版本中不起作用)。

#2


0  

You could also do

你也可以这样做

a.each_with_index.map {|aa, i| aa | b[i] }

#3


0  

a.zip(b).map{|x|x.flatten.uniq}

#1


1  

If you have the values in a and b, then

如果你有a和b中的值,那么

a.zip(b).map { |aa, bb| (aa + bb).uniq }

If you really want to put it onto the Array class, you can either monkey-patch it (not really recommended, especially for something this specific), or refine it (new, won't work in older versions).

如果你真的想把它放到Array类上,你可以对它进行修补(不是真的推荐,特别是对于这个特定的东西),或者改进它(新的,在旧版本中不起作用)。

#2


0  

You could also do

你也可以这样做

a.each_with_index.map {|aa, i| aa | b[i] }

#3


0  

a.zip(b).map{|x|x.flatten.uniq}