Ruby product array method
In ruby programming language, product() array methods are returns all combinations of given perimeter and self array. Syntax of this method as follows.
Array.product(other_array, ...) → new array
Parameters of this method is form of array. And length of resultant combination is product of self and parameter. That parameter of this method is optional, In case not provide parameter value result array contains self single element array.
Ruby product() method example
This section mentions some examples that are based on the concept of the product() method.
# Our array
record = ['a','b','c']
data = [1,2]
# product operation
p = record.product(data)
# Display record
print("record : ",record)
# Display result
print("\n p : ",p)

record : ["a", "b", "c"]
p : [["a", 1], ["a", 2], ["b", 1], ["b", 2], ["c", 1], ["c", 2]]
When the parameter of this method zero or more than once.
# Our array
record = ['a','b','c']
p1 = record.product()
p2 = record.product([true],['x','y'])
# Display result
print(" p1 : ",p1)
print("\n p2 :",p2)

p1 : [["a"], ["b"], ["c"]]
p2 :[["a", true, "x"], ["a", true, "y"], ["b", true, "x"], ["b", true, "y"], ["c", true, "x"], ["c", true, "y"]]
When parameter contains empty array.
# Our array
record = ['a','b','c']
p1 = record.product([])
p2 = record.product([1],[])
p3 = record.product([1])
# Display result
print(" p1 : ",p1)
print("\n p2 : ",p2)
print("\n p3 : ",p3)

p1 : []
p2 : []
p3 : [["a", 1], ["b", 1], ["c", 1]]
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment