Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of Ruby "===" operator on Ranges

I recently started learning Ruby and i'm reading the following Ruby Manual.

In this manual they say the following (about Ranges):

A final use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range. This is done using ===, the case equality operator.

With these examples:

  • (1..10) === 5 » true
  • (1..10) === 15 » false
  • (1..10) === 3.14159 » true
  • ('a'..'j') === 'c' » true
  • ('a'..'j') === 'z' » false

After read about the Ruby "===" operator here, I found that this works on ranges because Ruby translates this to case statement.

So you may want to be able to put the range in your case statement, and have it be selected. Also, note that case statements translate to b===a in statements like case a when b then true end.

However I have the following question: why does the following command return true?

(1..10) === 3.14159 » true

Since (1..10) means [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], I expected that the result would be false.

like image 431
JMarques Avatar asked Dec 05 '12 15:12

JMarques


People also ask

What does === mean in Ruby?

In Ruby, the === operator is used to test equality within a when clause of a case statement. In other languages, the above is true.

What is the name of this operator === in Ruby?

Triple Equals Operator (More Than Equality) Ruby is calling the === method here on the class.

What is range operator in Ruby?

Ranges as Sequences This is a general and easy way to define the ranges in Ruby to produce successive values in the sequence. It has a start point and an end point. Two operators are used for creating ranges, one is Double Dot (..) operator and the another one is Triple Dot (…)


1 Answers

1..10 indicates a Range from 0 to 10 in the mathematical sense and hence contains 3.14259

It is not the same as [1,2,3,4,5,6,7,8,9,10].

This array is a consequence of the method Range#each, used by Enumerable#to_a to construct the array representation of an object, yielding only the integer values included in the Range, since yielding all real values would mean traversing an infinite number of elements.

like image 171
Eureka Avatar answered Jan 01 '23 21:01

Eureka