The Crystal Programming Language Forum

Converting an array to its elements

def f(x, y)
    return x + y
puts  f(2, 3)
values = [3, 4]
puts values
puts  f(values)  # expected 7

The f function expects two parameters. What if I have the values in an array? Can I somehow tell Crystal to pass the content of the array to the function. (In Python this would be done by prefixing variable with a star: f(*values).

Crystal can’t splat arrays at the moment. You basically have two options:

  1. Just manually pass args like f values[0], values[1]

  2. Combine 1 with an Array overload

def f(values : Array)
  f values[0], values[1]

f [1, 2]

EDIT: For reference: Splats and tuples - Crystal.

Option three is Tuple.from, useful if your array has mixed types:

f(*{Int32, Float64}.from(values))
1 Like

Thanks for all the replies!