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 1 year has passed since last update.

LocalJumpError: unexpected return

Last updated at Posted at 2022-06-06

結論

  • ブロックの中で早期returnを使うな
  • ブロックの中で、returnは呼べないので次の処理へ飛ばす場合はnextを使う

ブロックとは

  • hoges.each do | hoge | endhoges.each {|hoge| } のようなもの
  • 有名なところだとmapeachなどが存在する

参考

再現手順

# ブロックの中でreturnを呼び出す

numbers = [1,2,3,4,5]

numbers.each do |num|
   return if num % 2 == 0
end 

実行すると、以下のエラーが出る

LocalJumpError: unexpected return

解決策

  • returnを使わずに処理しよう
    • returnはそもそも関数の返り値を返すメソッド
  • 特に早期returnなどで利用する場合はnext文で対応しよう
  • 例)1-5の値で偶数の値をeven_numbersに入れたい場合

numbers = [1,2,3,4,5]

even_numbers = [] #ここに偶数の値を入れる

# NG 早期リターンを使う

numbers.each do |num|
   return num % 2 != 0
   even_numbers << num
end 

# OK next文で解決する

numbers.each do |num|
   next if num % 2 != 0 
   even_numbers << num
end 

# OK もっときれいにに書く場合
# select: https://qiita.com/shibukk/items/7dded3e74b0f7dbfb633

even_numbers = numbers.select(&:even?)

参考

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?