10

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.

Community
  • 1
  • 1
JMarques
  • 3,044
  • 4
  • 34
  • 55

1 Answers1

12

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.

Eureka
  • 5,985
  • 2
  • 22
  • 15