Combination of two arrays in Ruby

后端 未结 3 1772
情歌与酒
情歌与酒 2020-12-08 05:54

What is the Ruby way to achieve following?

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

I want an array:

=> [f(1,3) ,f(1,4) , f(2,3) ,f(2,4)]
         


        
3条回答
  •  青春惊慌失措
    2020-12-08 06:33

    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]]
    

    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) }
    

提交回复
热议问题