3

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
2
  • 2
    The most essential concept here is that you can use a "splat" (the asterisk *) to turn an array into sequential arguments. The posted answer includes a good example of this. Commented Aug 16, 2016 at 4:37
  • If any of the answers were helpful, please consider selecting the one you preferred. (I'd prefer saying this if there were more than one answer, but the question is several days old...) Commented Aug 20, 2016 at 22:51

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

A one liner return x==1 ? arr : arr.product(*[arr]*(x-1)) :)
I'd probably use the array constructor to avoid confusion between the two *'s, i.e. arr.product(*Array.new(x - 1, arr))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.