Ruby method with maximum number of parameters

Nikita Barsukov picture Nikita Barsukov · Feb 11, 2011 · Viewed 37.8k times · Source

I have a method, that should accept maximum 2 arguments. Its code is like this:

def method (*args)
  if args.length < 3 then
    puts args.collect
  else
    puts "Enter correct number of  arguments"
  end
end

Is there more elegant way to specify it?

Answer

Simone Carletti picture Simone Carletti · Feb 11, 2011

You have several alternatives, depending on how much you want the method to be verbose and strict.

# force max 2 args
def foo(*args)
  raise ArgumentError, "Too many arguments" if args.length > 2
end

# silently ignore other args
def foo(*args)
  one, two = *args
  # use local vars one and two
end

# let the interpreter do its job
def foo(one, two)
end

# let the interpreter do its job
# with defaults
def foo(one, two = "default")
end