【发布时间】:2014-01-22 13:53:55
【问题描述】:
我正在尝试重新创建可在“Projects: Advanced Building Blocks”中找到的 Enumerable 的 count 方法。
Ruby 文档中的定义是 count
"通过枚举返回枚举中的项数。如果给定参数,则计算枚举中等于item的项数。如果给定块,则计算产生真值的元素数量。”
默认参数到底是什么?
到目前为止,我的处理方式如下: 当没有参数传递时,参数被设置为:
案例,当self不是字符串时:
当给定参数和给定块时(例如
[1,2,3].count(3) { |x| x == 3 }): 返回参数的警告和计数。当给定参数并且没有阻塞时(例如
[1,2,3].count(3)): 返回参数的计数。当没有参数并且没有块时(例如
[1,2,3].count): 返回实例的大小。else(没有给出参数并给出块)(例如
[1,2,3].count { |x| x == 3 }: 根据块中给出的规范返回计数。
我的两个问题基本上是:
- count 的默认参数是什么?
- 警告中使用的全局变量是什么?
这是我的代码:
module Enumerable
def my_count arg='default value'
if kind_of? String
# code
else # I think count works the same way for hashes and arrays
if arg != 'default value'
count = 0
for index in 0...size
count += 1 if arg == self[index]
end
warn "#{'what goes here'}: warning: block not used" if block_given?
count
else
return size if arg == 'default value' && !block_given?
count = 0
for index in 0...size
count += 1 if yield self[index]
end
count
end
end
end
end
【问题讨论】:
-
自 Ruby 1.9 起,Enumerable 不再被 String 类混入,因此您可以假设接收者不是字符串。没有默认参数。有可变数量的参数:零或一。你想要
def my_count(*args),然后检查args.size,它可以是零、一或多于一。 (如果不止一个,您可能需要引发ArgumentError异常)。
标签: ruby enumerable