Given an array of arguments, how do I send those arguments to a particular function in Ruby?

RubyArraysFunctionArguments

Ruby Problem Overview


Forgive the beginner question, but say I have an array:

a = [1,2,3]

And a function somewhere; let's say it's an instance function:

class Ilike
  def turtles(*args)
    puts args.inspect
  end
end

How do I invoke Ilike.turtles with a as if I were calling (Ilike.new).turtles(1,2,3).

I'm familiar with send, but this doesn't seem to translate an array into an argument list.

A parallel of what I'm looking for is the Javascript apply, which is equivalent to call but converts the array into an argument list.

Ruby Solutions


Solution 1 - Ruby

As you know, when you define a method, you can use the * to turn a list of arguments into an array. Similarly when you call a method you can use the * to turn an array into a list of arguments. So in your example you can just do:

Ilike.new.turtles(*a)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStevenView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow