我有一个方法,它应该接受最多 2 个参数。它的代码是这样的:
def method (*args)
if args.length < 3 then
puts args.collect
else
puts "Enter correct number of arguments"
end
end
有没有更优雅的方式来指定它?
最佳答案
您有多种选择,具体取决于您希望方法的冗长和严格程度。
# 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
关于具有最大参数数量的 Ruby 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4967735/