July 26th, 2024

The evolution of Ruby's Range class

The article details the Ruby Range class's evolution, its uses in programming, comparisons with other languages, and key updates, including endless ranges and methods for value testing and iteration.

Read original articleLink Icon
The evolution of Ruby's Range class

The article discusses the evolution and design of the Ruby Range class, emphasizing its significance in programming. A Range in Ruby is defined by two boundaries and can represent both discrete and continuous values. The article outlines the main uses of ranges, including iteration, value testing, and collection slicing, and compares Ruby's implementation with other programming languages like Python, C#, Rust, Kotlin, and Scala.

The history of Ruby's versions is traced, highlighting key changes in the Range class from its inception in 1996 to the latest updates in Ruby 3.3. The article explains how methods like #include? and #cover? were developed to check if a value belongs to a range, with #=== being used in pattern matching. Notably, Ruby 2.6 saw a change where #=== was modified to use #cover? for consistency.

The article also touches on the types of values that can serve as range boundaries, noting that they must be comparable. It introduces the concept of "endless" ranges, which were added in Ruby 2.6, allowing for ranges that extend indefinitely. The discussion concludes with examples of how ranges can be utilized in various contexts, including array slicing and conditional statements, showcasing their versatility in Ruby programming.

Link Icon 4 comments
By @jeffparsons - 5 months
Ruby's Range class has plenty of bugs to offer if you use it with anything except numbers, especially if you use any of its more "exotic" features.

I guess this isn't super constructive, but to me the whole thing smells of not just a lack of discipline, but a lack of _interest_ in correctness that seems to be endemic in the Ruby community.

We ended up writing our own `TimeRange` class to paper over the base Range bugs that show up if you use it with times.

One awkward takeaway from the experience is that I've come to believe that sometimes it _is_ worth unit testing other people's code, counter to the popular advice.

By @jballanc - 5 months
Nice write-up, but no discussion of Ruby's Range class is complete without at least a mention of the venerable flip-flop!

Can you predict the output of the following?

    (1..20).each do |i|
      puts i if i.odd?..i.prime?
    end
By @robertpohl - 5 months
I love the simplicity of Ruby!