简体   繁体   English

Ruby中链接比较的最佳实践

[英]Best practice for chaining comparisons in Ruby

In python, it is possible to chain comparisons like so: 在python中,可以像这样链接比较:

0 < 1 < 2 and 5 > 4 > 3

The only practice I can figure to accomplish similar in Ruby is like so: 我能想到在Ruby中完成类似的唯一实践是这样的:

0 < 1 && 1 < 2 && 5 > 4 && 4 > 3

Which I find to be fairly unappealing visually. 我觉得在视觉上没有吸引力。

I've searched google and found some class extensions to make Ruby work like Python, but I was wondering if there was an easier way to chain comparators using just core ruby? 我已经在google上搜索了,发现了一些类扩展以使Ruby像Python一样工作,但是我想知道是否有更简单的方法可以仅使用核心ruby链接比较器?

1.between?(0,2)

between? works for any class which includes the Comparable module, eg dates, strings, arrays etc. 适用于任何包含Comparable模块的类,例如日期,字符串,数组等。

If you have basic lower and upper bounds you can use Enumberable#include? 如果您具有基本的上限和下限,则可以使用Enumberable#include? for range comparison like: 进行范围比较,例如:

i = 10
(5 .. 20).include?(i)

So you know 5 is your lower-bound and 20 is your upper-bound. 因此,您知道5是您的下限,而20是您的上限。

Enumberable#include? uses == under the hood so it has to walk the range and compare each element, so this is poor performance for large ranges 在引擎盖下使用== ,因此它必须遍历范围并比较每个元素,因此对于大范围而言这是较差的性能

Edit: steenslag answer above is way better. 编辑: steenslag答案答案更好。 use that! 用那个!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM