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?
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