Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 497
Drakken Saer Avatar asked May 08 '26 20:05

Drakken Saer


2 Answers

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.

like image 146
Lukasz Muzyka Avatar answered May 10 '26 11:05

Lukasz Muzyka


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"])
like image 28
Alex Avatar answered May 10 '26 13:05

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!