Range evaluation in Ruby
This one is about performance.
In Ruby, whenever we evaluate if an object lies inside a range, we can use cover?
to ask Ruby to figure it out logically using the lower and upper limit; rather than using include?
which would instantiate each element of the range and then perform the evaluation on each instance of the range.
Using: include?
(1..10).include?(7) # true
Compares to performing all these evaluations:
1 == 7 # false
2 == 7 # false
3 == 7 # false
4 == 7 # false
5 == 7 # false
6 == 7 # false
7 == 7 # true
Using: cover?
(1..10).cover?(7) # true
Compares to performing this single evaluation:
7 >= 1 && 7 <= 10 # true
cover?
has performance advantages on large ranges or on more complex objects; like Date objects.
You can find more information about cover?
and include?
on the ruby-doc website.