I asked a question yesterday about comparing ranges for overlap and its been stuck in my throat ever since.
The consensus seems to be that my preferred answer which involves using the array intersection operator (&), is inefficient because comparing arrays is costly.
I wonder then, why this feature is in the language? Could it be that the language creators believed that sometimes you need an elegant way to achieve a solution even if it’s expensive to do so? Is comparing arrays so costly that you should avoid it whenever possible? The whole attraction of Ruby for me is the focus on syntactic elegance over premature optimization.
&is not a particularly inefficient method. I think you misunderstood the criticism of the accepted answer.Your preferred solution is inefficient because it converts the ranges to arrays.
A range such as
1..10000has a relatively small memory footprint – it only stores the start and end points. But if you convert it to an array, you allocate memory for all 10,000 entries.