OneNeptune
OneNeptune

Reputation: 913

Best practice for chaining comparisons in Ruby

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

Answers (2)

Cody Caughlan
Cody Caughlan

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

steenslag
steenslag

Reputation: 80075

1.between?(0,2)

between? works for any class which includes the Comparable module, e.g. dates, strings, arrays etc.

Upvotes: 5

Related Questions