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:
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.
In Ruby, the === operator is used to test equality within a when clause of a case statement. In other languages, the above is true.
Triple Equals Operator (More Than Equality) Ruby is calling the === method here on the class.
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..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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With