Reputation: 913
In python, it is possible to chain comparisons like so:
0 < 1 < 2 and 5 > 4 > 3
The only practice I can figure to accomplish similar in Ruby is like so:
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?
Upvotes: 1
Views: 507
Reputation: 32758
If you have basic lower and upper bounds you can use 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.
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. use that!
Upvotes: 3
Reputation: 80075
1.between?(0,2)
between?
works for any class which includes the Comparable module, e.g. dates, strings, arrays etc.
Upvotes: 5