问题
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?
回答1:
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
回答2:
if the maximum is two arguments, why use the splat operator like that at all? Just be explicit. (unless there is some other constraint that you haven't told us about.)
def foo(arg1, arg2)
# ...
end
Or...
def foo(arg1, arg2=some_default)
# ...
end
Or even...
def foo(arg1=some_default, arg2=some_other_default)
# ...
end
回答3:
Raise an error better. If the arguments are not correct, this is serious problem, which shouldn't pass in your with a humble puts
.
def method (*args)
raise ArgumentError.new("Enter correct number of arguments") unless args.length < 3
puts args.collect
end
来源:https://stackoverflow.com/questions/4967735/ruby-method-with-maximum-number-of-parameters