3

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?

1
  • 1
    Without * you could just write my_method(model_name, ary[0], ary[1], ary[2]), not much of a problem here ;-) Commented Feb 28, 2017 at 7:53

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It is a very good way, I didn't know the splat operator before ;)
You saved me hours of frustration.
@Alex yeah, pretty handy. I use it all the time when I deal with CSVs and have variable number of columns per row
1

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"])

2 Comments

You could also use id_var, attribute_1, attribute_2 = data to assign the elements to variables.
you are right, but maybe this way is more readable or easy to understand

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.