Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of the arguments a method is called with

How do I get a list of the arguments passed to a method, preferably one that I can iterate through?

For example something like

def foo(a,b,c)
  puts args.inspect
end

foo(1,2,3)
=> [1,2,3]

? Thanks!

like image 228
Allyl Isocyanate Avatar asked Feb 24 '23 00:02

Allyl Isocyanate


1 Answers

You can always define a method that takes an arbitrary number of arguments:

def foo(*args)
  puts args.inspect
end

This does exactly what you want, but only works on methods defined in such a manner.

The *args notation means "zero or more arguments" in this context. The opposite of this is the splat operator which expands them back into a list, useful for calling other methods.

As a note, the *-optional arguments must come last in the list of arguments.

like image 65
tadman Avatar answered Feb 26 '23 22:02

tadman