Ruby中两个数组的组合 [英] Combination of two arrays in Ruby
本文介绍了Ruby中两个数组的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ruby遵循以下方式是什么?
What is the Ruby way to achieve following?
a = [1,2]
b = [3,4]
我想要一个数组:
=> [f(1,3) ,f(1,4) , f(2,3) ,f(2,4)]
推荐答案
您可以使用 product
首先获取数组的笛卡尔积,然后收集函数结果
You can use product
to get the cartesian product of the arrays first, then collect the function results.
a.product(b) => [[1, 3], [1, 4], [2, 3], [2, 4]]
因此您可以使用 map
或 collect
来获取结果。对于同一方法,它们是不同的名称。
So you can use map
or collect
to get the results. They are different names for the same method.
a.product(b).collect { |x, y| f(x, y) }
这篇关于Ruby中两个数组的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文