Ruby: 检查从实例化 class 传递到模块方法的参数数量

Ruby: Check number of arguments passed from instantiated class to the method of a module

我正在尝试查找从我的实例化 class 传递到模块方法的参数数量。

class A
  inclue ModuleA
end

A.new.moduleA_method(arg1, arg2, arg3)

这是模块 A 中的内容

moduleA
   def moduleA_method(arg1, arg2, arg3)
     puts ARGV.size
   end
end

ARGV.size 打印 0,但根据我的理解应该是 3。

接近但不完全。 ARGV 常量实际上包含传递给脚本而不是方法的所有参数。因此,如果您使用参数从命令行调用脚本,那么它们将位于此常量中。

如果名为 "example.rb" 的脚本包含:

puts ARGV.length

如果您像这样在命令行上调用它:

> ruby example.rb

你会得到0

如果你这样称呼它:

> ruby example.rb an_argument

你会得到1

您可以使用method 方法将方法作为对象获取。然后调用 arity 以获取该方法的参数数量。

MyClass.new.method(:some_method).arity

__method__returns当前方法的名称作为符号。

综合起来:

class Foo
  def bar(arg1, arg2)
    self.method(__method__).arity # => 2
  end
end

好吧,首先没有人提到定义这样的方法签名这一事实

def some_method(arg1,arg2,arg3)

将需要 3 个参数,否则您将得到一个 ArgumentError: wrong number of arguments (0 for 3) 或您传入的参数数量。因此,在方法中引用 arity 是无用的,因为您无法在不知道所需参数数量的情况下克服错误。

但是你可以定义一个像

这样的方法
def some_method(*args)
  puts args.size
end

这将收集传入的尽可能多或尽可能少的参数,并将它们包装在一个数组中,例如

some_method 
0
#=> nil
some_method "a","b","c"
3 
#=> nil

这允许完全灵活的论点,我认为根据我对你的阅读方式,你正在寻找的更多 post