Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing ranges in Ruby

Tags:

range

ruby

Why does this equation return false

(0..9) === (0..9)
=> false

While this equation returns true...

5 === 5
=> true

And this equation is also true?

(0..9) == (0..9)
=> true

What am I missing about ranges?

like image 251
stevenspiel Avatar asked Feb 15 '23 16:02

stevenspiel


2 Answers

The Range class redefines the === operator to check if the argument on the right is within the range per http://www.ruby-doc.org/core-1.9.3/Range.html#method-i-3D-3D-3D, which is why you're seeing what you're seeing.

like image 104
Peter Alfvin Avatar answered Mar 16 '23 13:03

Peter Alfvin


Range#=== documentation says:

Returns true if obj is an element of the range, false otherwise. Conveniently, === is the comparison operator used by case statements.

The range (0..9) is not an element of the range (0..9), which is why (0..9) === (0..9) is false.

Range#== documentation says:

Returns true only if obj is a Range, has equivalent begin and end items (by comparing them with ==), and has the same exclude_end? setting as the range.

The start and end items of the ranges (0..9) and (0..9) are the same, which is why (0..9) == (0..9) is true.

like image 36
Justin Ko Avatar answered Mar 16 '23 13:03

Justin Ko