`Range#include?` 和 `Range#cover?` 有什么区别? [英] What is the difference between `Range#include?` and `Range#cover?`?

查看:49
本文介绍了`Range#include?` 和 `Range#cover?` 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑 修正了以下 toro2k 的评论.

Edit Fixed following toro2k's comment.

Range#include?Range#cover? 在源代码中似乎有所不同 1, 2,它们的效率不同.

Range#include? and Range#cover? seem to be different as seen in the source code 1, 2, and they are different in efficiency.

t = Time.now
500000.times do
    ("a".."z").include?("g")
end
puts Time.now - t    # => 0.504382493

t = Time.now
500000.times do
    ("a".."z").cover?("g")
end
puts Time.now - t    # => 0.454867868

看源码,Range#include?似乎比Range#cover?复杂.为什么Range#include?不能只是Range#cover的别名?它们有什么区别?

Looking at the source code, Range#include? seems to be more complex than Range#cover?. Why can't Range#include? be simply an alias of Range#cover? What is their difference?

推荐答案

这两种方法的设计目的是为了做两件略有不同的事情.在内部,它们的实现方式也非常不同.您可以查看文档 并看到 .include?.cover?

The two methods are designed to do two slightly different things on purpose. Internally they are implemented very differently too. You can take a look at the sources in the documentation and see that .include? is doing a lot more than .cover?

.cover? 方法与 Comparable 模块相关,并检查项目是否适合排序列表中的端点之间.即使该项目不在 Range 隐含的集合中,它也会返回 true.

The .cover? method is related to the Comparable module, and checks whether an item would fit between the end points in a sorted list. It will return true even if the item is not in the set implied by the Range.

.include? 方法与Enumerable 模块相关,检查一个项目是否确实在Range.数字有一些技巧 - 整数范围被算作包括所有隐含的 Float 值(我不知道为什么).

The .include? method is related to the Enumerable module, and checks whether an item is actually in the complete set implied by the Range. There is some finessing with numerics - Integer ranges are counted as including all the implied Float values (I'm not sure why).

这些示例可能会有所帮助:

These examples might help:

('a'..'z').cover?('yellow')
# => true

('a'..'z').include?('yellow')
# => false

('yellaa'..'yellzz').include?('yellow')
 => true

另外,如果你尝试

('aaaaaa'..'zzzzzz').include?('yellow')

你应该注意到它比

('aaaaaa'..'zzzzzz').cover?('yellow')

这篇关于`Range#include?` 和 `Range#cover?` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆