Drakken Saer
Drakken Saer

Reputation: 889

How to pass array elements as separate method arguments in Ruby?

Scenario: A method takes arguments in this fashion

def my_method(model_name, id, attribute_1, attribute_2)
  # ...
end

All parameters are unknown, so I am fetching the model name from the object's class name, and the attributes I am fetching from that class returned as an array.

Problem: I have an array ["x", "y", "z"]. I need to take the items from each array and pass them into the method parameters after the Model as illustrated above.

Is it even possible to "drop the brackets" from an array so to speak, but keep the items and their order in tact?

Upvotes: 3

Views: 2425

Answers (2)

Alex
Alex

Reputation: 1260

The easy way is:

data = ["x", "y", "z"]
my_method(model_name, data[0], data[1], data[2])

The long way:

data = ["x", "y", "z"]
id_var = data[0]
attribute_1 = data[1]
attribute_2 = data[2]
my_method(model_name, id_var, attribute_1, attribute_2)

But the best and smartest way is the one that proposed Stefan and Lukasz Muzyka:

my_method(model_name, *["x", "y", "z"])

Upvotes: 1

Lukasz Muzyka
Lukasz Muzyka

Reputation: 2783

yes, just use * before array:

my_method(model_name, *["x", "y", "z"])

it will result in:

my_method(model_name, "x", "y", "z")

* is a splat operator.

Upvotes: 11

Related Questions