具有最大参数数量的 Ruby 方法

标签 ruby variadic-functions

我有一个方法,它应该接受最多 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/

相关文章:

java - slf4j 是否有 Java 1.5 varargs API?

ios - 如何通过 CocoaPods 安装后 Hook 修改 OTHER_LDFLAGS?

ruby - 我如何将 "require"放入当前范围?

ruby - 如何将此 Controller 代码移动到 Resque 作业?

ruby - 在 ruby​​ 程序中记录到 STDOUT(不适用于 Docker)

c - 可变记录器调度程序

c - C printf 函数如何知道传递的整数大小?

ruby - Gitlab - NoMethodError(未定义的方法 `tag_names' 为 nil :NilClass):

c++ - 为什么 C++ 不支持强类型省略号?

c++ - 如何声明省略号定义的 va_list 未使用