Ruby 2.7 raises pattern matching to the next level

Ruby By Alex Mit via Shutterstock

The team behind the programming language Ruby followed its tradition of around-Christmas-releases and gifted its community Ruby 2.7 with features like experimental pattern matching and a compaction method for its garbage collection.

It also made some changes to prepare developers for the release of Ruby 3, which for example won’t automatically converse keyword arguments and positional arguments anymore. Instead, the two will be separated, which might make some code updates necessary. Devs who used the old behaviour will receive warnings in version 2.7, informing them about future incompatibilities.

One of the most highlighted additions in Ruby 2.7 is the still experimental pattern matching feature. With it, developers can specify patterns data should conform to and check if it does. 

Efforts of getting refined pattern matching capabilities into the language started with a proof of concept in 2012 and a first prototype in 2016. The goals of the new feature included backwards compatibility and a “Ruby-ish” feel, since pattern matching can mostly be found in statically typed functional programming languages. Ruby meanwhile follows a dynamically typed and object-oriented approach, which could explain why the addition of pattern matching took a while. 

Advertisement

According to a feature introduction from April 2019, pattern matching in Ruby boils down to an extension of case expressions so that multiple assignments can be used. While the latter isn’t anything new per se, the combination allows for checking an object’s structure. Often cited use cases in Ruby include the handling of JSON data, which can be done in a more efficient manner with pattern matching.

Friends of the project’s trunk had the chance to take the implementation for a spin since last spring at least. However, as part of an official release Ruby creators should be able to gather even more feedback to advance the component.

To help developers who suffer speed degradation when running multi-threaded programs, Ruby 2.7 includes a new garbage collection method called GC.compact. It compacts live objects in a heap and therefore defragments memory spaces, improving performance for copy-on-write operations.

Apart from that, the Ruby team has been busy improving the bundled interactive environment irb. In the current release, devs are able to do multi-line edits and display references for a given class, module, or method. Added colourisation of source lines and inspect results is meant to make the tools output more helpful. 

A complete list of changes can be found on the official Ruby website.

- Advertisement -