9

我有一个带有可变数量参数的函数,如下所示:

def myfun(*args)
  # ...
end

所有 args 都是相同的类型 ( Symbol),所以现在我记录这个函数,就像只有一个参数一样,说它可以接受多个参数,例如:

# this function doesn’t do anything
# @param [Symbol]: this argument does something, you can add more symbols
#                  if you want
def myfun(*args)
  # ...
end

有没有内置的方法来处理这种情况?

4

2 回答 2

10

以下是有意义的,因为args它是Array方法内部的,尽管没有任何参数是Array这样的:

# this function doesn’t do anything
#
# @param [Array<Symbol>] args these arguments do something
# @return [nil]
def myfun(*args)
  # ...
end

请注意,*从注释中的参数名称中删除。这只是为了保持一致 -args 一个Array,但*args不是。

快速搜索显示了很多使用这种风格的项目,包括在 Yard 自己的 .rb 文件中(例如,参见Verifier 类中的初始化源代码)——尽管指南中没有给出这种约定的示例。

于 2014-04-27T20:57:09.897 回答
3

据我所知,尼尔斯莱特的答案是非结构化参数列表的最佳答案。

但是对于用于*args接受任何一组固定的可能参数列表的方法,有@overload. 例如,对于Enumerable#find_index,可以这样写:

# Compares each entry in _enum_ with value or passes to _block_.
# Returns the index for the first for which the evaluated value
# is non-false. If no object matches, returns `nil`.
# 
# @overload find_index(value)
#   Finds the first index of the specified value.
#   @param value [Object] the value to find
#   @return [Integer, nil] the index, or `nil` if no element matches
# @overload find_index(&block)
#   Finds the index of the first value matching
#   the specified block.
#   @yieldparam [Object] element the element to match against
#   @yieldreturn [Boolean] whether the element matches
#   @return [Integer, nil] the index, or `nil` if no element matches
# @overload find_index
#   @return [Enumerator] a new enumerator
def find_index(*args)
  # (...)
end

这将被记录为:

#find_index(值)⇒整数
#find_index {|元素| ... } ⇒ 整数
#find_index ⇒ 枚举器

将enum中的每个条目与 value 进行比较或传递给block。返回评估值为非假的第一个索引。如果没有对象匹配,则返回nil

重载:

#find_index(值)⇒整数

查找指定值的第一个索引。

(...ETC。)

于 2021-01-29T20:13:21.913 回答