string.include的奇怪行为?在Ruby中

时间:2013-10-25 07:04:44

标签: ruby string

我不明白为什么include?在两种情况下都会返回true。有人可以开导我吗?

"".include?("") # => true
"stackoverflow".include?("") # => true

documentation州:

include? other_str → true or false
Returns true if str contains the given string or character.

2 个答案:

答案 0 :(得分:7)

因为string" stackoverflow"在字母/字符之间包含无限数量的空字符串。

答案 1 :(得分:1)

这不是一个错误。 countinclude?的工作方式截然不同。 include?检查子字符串,但count的说明

  

[每个参数]定义要计数的一组字符。该   这些集合的交集定义了要在str中计算的字符。

通过仅提供空字符串作为参数,您告诉count不计算任何字符。在这种情况下返回的唯一合理的事情是0。