10 new features in Ruby 2.5

This is a guest post by Junichi Ito (@jnchito). Junichi is a Ruby programmer at SonicGarden.jp, translator of Everyday Rails Testing with RSpec, and one of the most popular Ruby writers/bloggers in Japan

Ruby 2.5.0-preview1 was released on October 10 2017. It introduces lots of new features and performance improvements. I have handpicked 10 new features to go over. I hope this article will help you understand some of the coming changes available in Ruby 2.5!

rescue/else/ensure are allowed inside do/end blocks without begin/end

You can write rescue/else/ensure clauses without begin/end keyword within do/end blocks:

But you’ll get an error if you use {} blocks:

Top-level constant lookup is removed

In Ruby 2.4, the following code works with a warning:

This is because the top-level constants are defined under Object class, and Ruby tries to look up the superclass of Staff class, and eventually finds ItemsController under the Object class which is a superclass of Staff class. The details were discussed here:

But in Ruby 2.5, Ruby won’t look up superclass. So the previous code fails with error:

Bundler gem is now bundled

Bundler is bundled as a standard library. So you can use it without gem install bundler!

Print backtrace and error message in reverse order (experimental)

In Ruby 2.5, backtrace and error message are printed in reverse order. For example, in Ruby 2.4:

In Ruby 2.5:

As of preview1, this is an experimental feature and applied only when STDERR is unchanged and a tty.

Kernel#yield_self

Kernel#yield_self is introduced. This method takes a receiver as a block argument and returns a block value as it is:

String#delete_prefix/delete_suffix

String#delete_prefix/delete_suffix can remove prefix and suffix from a string:

Array#prepend/append as aliases of unshift/push

Array#prepend/append are added as aliases of unshift/push methods:

Hash#transform_keys/transform_keys!

Hash#transform_keys can change keys according to the return value of a block:

transform_keys! is a destructive version:

Dir.children/each_child

You might have used Dir.entries method:

If you want to remove “.” and “..” from the returned values, you can Dir.children instead:

Dir.each_child returns not an array but an Enumerator object:

ERB#result_with_hash

The following code shows how to assign local variables to ERB template in Ruby 2.4:

But in Ruby 2.5, you can rewrite with ERB#result_with_hash like this:

Other changes

You can find other changes on the Ruby 2.5 NEWS page: NEWS for Ruby 2.5.0

Love Ruby 2.5!

This entry was posted in Community and tagged . Bookmark the permalink.

One Response to 10 new features in Ruby 2.5

  1. Philippe Creux says:

    Thanks for taking the time to sharing that!

Leave a Reply

Your email address will not be published. Required fields are marked *