In this article, we’re going to explore the following topics:

The .. operator

operator The … operator

operator Ranges and floating values

Feel free to read the Case statement behind the scene article if you’re not familiar with the case statement and the when clause.

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

The when clause with range

In a case statement the when clauses can take a range as parameter

Here, the case statement takes an integer as parameter.

As the when clause takes a range as parameter then the Range#=== operator is invoked and it checks if the integer is included in the range.

The .. operator in our range ensures the left and the right operands are included in the range.

The second when clause takes a range using the … operator.

This means that the right operand isn’t included in the range.

Now that we’re more familiar with the when clause and ranges, let’s break down an edge case that I encountered using floats and ranges.

Range of floating values and the when clause

As we’ve seen in the above example, the … operator excludes the right operand of the range. But, what if I want to exclude the left operand?

Here, only the content of the first when clause that matches against the surface value is processed — in our case when 70..90 then :second_value .

In this case, the case statement returns :second_value .

So the next when clause is never evaluated for a surface of 90 .

This works fine for a range of integers.

But what if we have to deal with a range of floats?

Here, the case statement return :third_value as surface is strictly greater than 130.0 .

if we reassign surface = 130.0 then our case statement returns :second_value — same as ranges of integers.

Note that we use the Float::INFINITY constant to end our last range.

This is equivalent to any value above 130.0 .

Finally let’s have a look at the notion of endless ranges — This notion has been introduced in Ruby 2.6.0.

On line 6, the range explicitly omits the right operand.

Ruby interprets this as following: 130..Float::INFINITY

This allow us to avoid to implicitly call the Float::INFINITY to end our range.

So here, the value of surface matches against this comparison and the case statement returns :third_value .

Voilà!