(Ruby)如何检查一个范围是否包含另一个范围的子集? [英] (Ruby) How do you check whether a range contains a subset of another range?

查看:14
本文介绍了(Ruby)如何检查一个范围是否包含另一个范围的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个重叠的范围:

If I have two ranges that overlap:

x = 1..10
y = 5..15

当我说:

puts x.include? y 

输出是:

false 

因为这两个范围只是部分重叠.

because the two ranges only overlap partially.

但是,如果我希望在两个范围之间存在部分重叠时它是真实的",我该怎么写呢?换句话说,我需要一种方法来知道一个范围何时包含另一个范围的子集.我认为有一种用 Ruby 编写的优雅方法,但我能想到的唯一解决方案是冗长的.

But if I want it to be "true" when there is partial overlap between two ranges, how would I write that? In other words I need a way to know when one range contains a subset of another range. I assume there's an elegant way to write this in Ruby but the only solutions I can think of are verbose.

推荐答案

在大范围使用时要小心,但这是一种优雅的方式:

Be careful using this with large ranges but this is an elegant way to do it:

(x.to_a & y.to_a).empty?

这篇关于(Ruby)如何检查一个范围是否包含另一个范围的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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