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?
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.
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"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With