Mr. Kennedy Mr. Kennedy - 2 months ago 10
Ruby Question

Python vs Ruby: Is y greater than x and less than z?

Is there a less verbose way to compare three integer values in Ruby?

For example, in Python the following return True:

x = 2
y = 3
z = 4
x < y < z


With the same variable bindings in Ruby the following will both return true:

x < y && y < z
x.send(:<, y) && y.send(:<, z)


but this:

x < y < z


returns NoMethodError:

NoMethodError: undefined method `<' for true:TrueClass


I presume this is because the first comparison of
x < y
evaluates to
true
and the error is raised from the resulting
TrueClass.instance < z
? Is there a way in Ruby to compare three integer values without the use of &&?

Thank you.

Answer

You can write

(x+1...z).cover? y

or (my preference)

(x+1..z-1).cover? y

Because x, y and z are numeric, this is the same as

(x+1..z-1).include? y

See Range#cover? and Range#include?.