Ruby 2.7

Ruby 2.7 has just been released (Dec 25) as the tradition is. That’s the last minor version before 3.0 which is going to be released on Dec 25, 2020. In one year.

Here are a few new features that caught my eye.

Array intersection

There are a couple of set methods you can use with an array:

  • Array#union
  • Array#difference

Union helps you join two arrays together:

[1, 2, 3].union([4, 5])
=> [1, 2, 3, 4, 5, 6]

Difference returns an array with all the elements of the first array excluding the elements of the second array:

[1, 2, 3].difference([2, 3])
=> [1]

Ruby 2.7 gives us Array#intersection which returns an array with the common elements between the first and the second one:

[1, 2, 3].intersection([2, 3, 4])
=> [2, 3]

Named parameters

When you are iterating over an array, for example, you have to name the parameter that references the current element in the iteration in order to use it in the block:

[1, 2, 3].each { |n| puts "#{n}" }
1
2
3

With named parameters in Ruby 2.7, you can skip naming the parameter and use _1 instead:

[1, 2, 3].each { puts "#{_1}" }
1
2
3

Why? I don’t know. Convenience?

Enumerable#filter_map

If you want to filter and map an array, for example, at the same time now you can:

[1, 2, 3, 4].filter_map { _1 ** 4 if _1.even? }
=> [16, 256]

You will notice I am also using named parameters in the example above.

Pattern matching

An experimental feature in Ruby 2.7 is pattern matching. The way to do it is using the in keyword:

[1, 2, 3] in [a, b, c]
=> nil
a
=> 1
b
=> 2
c
=> 3

As you can see, Ruby matched 1, 2, 3 to a, b, c because there is a pattern it can recognize there. So it created three assignments to a, b, c with the equivalent values. There is much more to say about pattern matching, but it’s out of the scope of this article. You can check Pattern matching – New feature in Ruby 2.7 – Speaker Deck.

I hope you enjoy the new features. You can read Ruby 2.7.0 Released for more details.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s