0
0

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 3 years have passed since last update.

【Ruby】nextとreturn

Posted at

map関数などの繰り返しの処理の中で、
ある条件のときだけ次のループに行きそのまま処理を続けたいときはreturnじゃなくてnextを使う。

##next
nextはもっとも内側のループの次の繰り返しにジャンプします。

n + 1が偶数のときにputs "hello! #{n + 1}回目"を実行せずに次のループにいく。

def next_method
  5.times do |n|
    next if (n + 1).even?
    puts "hello! #{n + 1}回目"
  end
  puts "完了!"
end

next_method

#=>hello! 1回目
#=>hello! 3回目
#=>hello! 5回目
#=>完了!

##return
式の値を戻り値としてメソッドの実行を終了します。

n + 1が偶数のときに処理を抜けるので「2回目」は実行されない。

def block_return
  5.times do |n|
    return if (n + 1).even?
    puts "hello! #{n + 1}回目"
  end

  puts "完了!"
end

block_return

#=>hello! 1回目

##参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?