Allyl Isocyanate
Allyl Isocyanate

Reputation: 13626

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!

Upvotes: 4

Views: 7288

Answers (3)

Michael Kohl
Michael Kohl

Reputation: 66837

As others pointed out you can use the splat operator (*) for achieving what you want. If you don't like that, you can use the fact that Ruby methods can take a hash as last argument with nicer syntax.

def foo(args)
  raise ArgumentError if args.keys.any? { |arg| arg.nil? || !arg.kind_of?(Integer) }
end

puts foo(:a => 1, :b => 2, :c => "a") # raise an ArgumentError

To access the arguments inside the method you have to use args[:a] etc.

Upvotes: 2

tadman
tadman

Reputation: 211610

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.

Upvotes: 3

Emily
Emily

Reputation: 18193

If you define your method as you specified, you'll always have 3 args, or the method call is invalid. So "all the args" is already defined for you. So you would just change your method to:

def foo(a,b,c)
  [a, b, c]
end

To define a method that can be called with any args (and to then access those args) you can do something like this:

def foo(*args)
  args
end

What the * does is put all args after that point into an array.

Upvotes: 3

Related Questions