Reputation: 339
Is there a way have x amount of same parameters in Ruby?
Easiest way to ask this is, can you shorten this?
arr = [0,1,2,3]
if x == 1
return arr
elsif x == 2
return arr.product(arr)
elsif x == 3
return arr.product(arr, arr)
elsif x == 4
return arr.product(arr, arr, arr)
elsif x == 5
return arr.product(arr, arr, arr, arr)
end
Upvotes: 3
Views: 62
Reputation: 110685
You can obtain the desired result as follows.
def prod(arr, x)
return arr if x==1
arr.product(*[arr]*(x-1))
end
arr = [0,1,2,3]
arr == prod(arr, 1) #=> true
arr.product(arr) == prod(arr, 2) #=> true
arr.product(arr, arr) == prod(arr, 3) #=> true
arr.product(arr, arr, arr) == prod(arr, 4) #=> true
arr.product(arr, arr, arr, arr) == prod(arr, 5) #=> true
Upvotes: 8