Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination of two arrays in Ruby

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)] 
like image 608
pierrotlefou Avatar asked Oct 09 '09 13:10

pierrotlefou


People also ask

How do you combine arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

What is array combination?

Array#combination() : combination() is an Array class method which invokes with a block yielding all combinations of length 'n' of elements of the array. Syntax: Array. combination() Parameter: Arrays in which we want elements to be invoked Return: all combinations of length 'n' of elements of the array.

How do you append an array to another array in Ruby?

In this case, you can use the concat() method in Ruby. concat() is used to join, combine, concatenate, or append arrays. The concat() method returns a new array with all of the elements of the arrays combined into one.

How do you compare two arrays in Ruby?

Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.


1 Answers

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) } 
like image 81
Aaron Hinni Avatar answered Sep 28 '22 01:09

Aaron Hinni