我有两个嵌套数组:
one = [
["Hiking", "fishing", "photography"],
["The Avengers", "The Dark Knight", "Lord of the Rings"],
["Firefly", "Battlestar Galactica", "The Expanse"],
["The Hobbit", "1984", "Dune", "Ender's Game"]
]
two = [
["Hiking", "photography"],
["Whiplash", "Pulp Ficiton", "The Avengers"],
["Firefly", "Battlestar Galactica", "The Expanse"],
["The Hobbit", "1984", "Dune", "Ender's Game"]
]我想我可以逐个迭代和比较,但是有没有更好的方法呢?
发布于 2017-05-02 16:55:41
可能的解决方案(假设您希望通过数组对查找公共元素):
one.zip(two).flat_map { |f, s| f & s }.count
#=> 10发布于 2017-05-02 16:54:43
我会这样做:
(one.flatten & two.flatten).size
#=> 10发布于 2017-05-03 02:14:33
您可以考虑以下几点,以避免创建临时数组one.zip(two)。
one.size.times.reduce(0) { |t,i| t + (one[i] & two[i]).size }
#=> 10https://stackoverflow.com/questions/43733704
复制相似问题