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)]
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).
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.
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.
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.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With