Ruby 2.5 allows rescue/else/ensure inside do/end blocks

Amit Choudhary

By Amit Choudhary

on October 24, 2017

This blog is part of our  Ruby 2.5 series.

Ruby 2.4

1irb> array_from_user = [4, 2, 0, 1]
2  => [4, 2, 0, 1]
3
4irb> array_from_user.each do |number|
5irb>   p 10 / number
6irb> rescue ZeroDivisionError => exception
7irb>   p exception
8irb>   next
9irb> end
10SyntaxError: (irb):4: syntax error, unexpected keyword_rescue,
11expecting keyword_end
12rescue ZeroDivisionError => exception
13      ^

Ruby 2.4 throws an error when we try to use rescue/else/ensure inside do/end blocks.

Ruby 2.5.0-preview1

1irb> array_from_user = [4, 2, 0, 1]
2  => [4, 2, 0, 1]
3irb> array_from_user.each do |number|
4irb>   p 10 / number
5irb> rescue ZeroDivisionError => exception
6irb>   p exception
7irb>   next
8irb> end
92
105
11#<ZeroDivisionError: divided by 0>
1210
13 => [4, 2, 0, 1]

Ruby 2.5 supports rescue/else/ensure inside do/end blocks.

Here is relevant commit and discussion.