Ruby 2.5.0 New Features

 New features

 The Ruby team has a tradition of releasing new Ruby versions during Christmas. 2017 is no exception as they released Ruby 2.5.0. This is the first stable release of the Ruby 2.5 series.

Ruby 2.5.0 comes with new features and performance improvements. Let's take a look at some of the features with sample code.

rescue on blocks

rescue/else/ensure are now allowed to be used directly with do/end blocks

Before Ruby 2.5.0, you need to use begin and end to be able to use rescue.

lambda do
    raise 'err'
    $! # => #<RuntimeError: err>

Starting with Ruby 2.5.0, you can remove begin and the corresponding end.

lambda do
  raise 'err'
  $! # => #<RuntimeError: err>

It looks cleaner and though Matz isn't a big fan of the syntax, he knows many developers like it. So, thank you Matz!


yield_self accepts a block and returns the result of the block.

The block below returns the square of the object.

3.yield_self{ |x| x*x }
 => 9

Ruby already has tap but it returns the object instead of the result of the block.

3.tap{ |x| x*x }
 => 3

New Hash methods

slice returns a hash containing the given keys.

{ a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b)
 => {:a=>1, :b=>2} 

transform_keys and transform_keys! returns a new hash with the keys converted using the block.

{ a: 1, b: 2, c: 3, d: 4 }.transform_keys{ |k| k.to_s }
 => {"a"=>1, "b"=>2, "c"=>3, "d"=>4} 

These methods are from ActiveSupport though slice! didn't make the cut!

Keyword arguments on

You can add keyword_init: true to to be able to use keyword arguments.

Before Ruby 2.5.0, you can't use keyword arguments.

Point =, :y), 5)
 => #<struct Point x=3, y=5> 

You need to pass x first, then y. This is not a problem when you only have 2 attributes but it's a pain if you have a lot more attributes.

On Ruby 2.5.0, you can add keyword_init: true.

Point =, :y, keyword_init: true) 3, y: 5)
 => #<struct Point x=3, y=5> 

If you use keyword_init: true, you can't use, 5). Otherwise you'll get ArgumentError (wrong number of arguments (given 2, expected 0)).

Pattern argument on Enumerable methods

You can pass a pattern on all?, any?, none?, and one? to make code more concise. If a pattern is passed instead of a block, the === method is used.

[1, 3.14, 2ri].all?(Numeric)
 => true

The code above is equivalent to

[1, 3.14, 2ri].all?{ |x| Numeric === x }
 => true 

Another common use for this is passing regex.

%w{ant bear cat}.none?(/d/) 
 => true

The code above is equivalent to

%w{ant bear cat}.none?{|x| /d/ === x }
 => true

Other features

Check out more features and improvements on the announcement blog and the commit logs. 

Are you ready to test your deployment with Engine Yard
Try Free 500 hours Trial

Ruby on Rails

Related posts


Subscribe to our Blog