LoginSignup
0
0

More than 1 year has passed since last update.

return/break/nextの使い方(Ruby)

Posted at

Ruby3.1
制御構造return
制御構造break
制御構造next

return

Rubyのようなオブジェクト指向の言語の関数をメソッドと呼ぶ
breakは式の値を戻り値としてメソッドを終了する

def ex
  10.times do |i|
    if i == 7
      return i
    end
  end
end
#メソッドexを実行します(戻り値はi)
ex 
#=> 7

#戻り値を省略するとnilが返る
def ex
  10.times do |i|
    if i == 7
      return
    end
  end
end
ex
#=> nil

break

breakは一番内側のループを脱出する

10.times do |i|
  if i == 3
    break
  end
  puts i
end
0
1
2

next

一番内側のループの繰り返しにジャンプする

5.times do |i|
  if i % 2 == 0
    next
  end
  puts i
end
1
3
0
0
0

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
0
0