1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby2.6] rescueのないelseとは?

1
Posted at

さて11月ですのでRuby2.6のリリースが迫ってきましたね。

個人的にはyield_selfの別名としてthenが追加されるのが大きそうです。

そんな訳でpreview版の情報を見てたんですが気になるものが

rescue 無しの else が文法エラーとなるようになりました [EXPERIMENTAL]

なんじゃこりゃ

調べてみたところ

begin
  hoge
else
  foo
end

というbegin節の中にrescueなしのelseがある場合に役立たずなのでエラーとするらしいです。


本当に役立たずなのか

実験

begin
  puts "hoge"
else
  puts "fooo"
end

puts "end"
hoge
fooo
end

基本的にelse節の中は実行されるので無意味のように見えます。

さて、Rubyのbeginにはもうひとつ意味があります。
それがbegin-while構文です。

begin-while
i = 0
begin
  i += 1
  puts "hoge"
else
  puts "fooo"
end while i < 3
puts "end"
hoge
fooo
hoge
fooo
hoge
fooo
end

どうやらelse内は毎度実行されるのでやっぱり無意味に見えます。

実は

rescueを使わずに例外(?)を飛ばしつつプログラムに復帰させる魔法みたいな構文があります。

i = 0
begin
  i += 1
  puts "hoge"
  break if i == 2
else
  puts "fooo"
end while i < 3
puts "end"

そうbreakです。
breakは実装として例外の一種を用いています。

結果

hoge
fooo
hoge
end

breakでの脱出時にはelse節を経由せずに脱出している事がわかります。

1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?