LoginSignup
9
6

More than 3 years have passed since last update.

【Ruby】next ifとは?ループ処理で特定の条件の場合は処理をスキップする

Posted at

個人メモです。

ループ処理の中のnext ifは指定した条件の場合、処理をスキップする。

▼実例1
forループを使った処理でnext ifを使った例。

even?メソッドで、iが偶数の場合のみtrueになり、表示処理P iをスキップする。

for x in 1...11
   next if x.even?
   p x
end

##出力結果
1
3
5
7
9



▼実例2

配列に対しmapメソッドを使った場合。
next if x.odd?によりxが奇数の場合はスキップとなる。

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = arr.map{|x|
  next if x.odd?
  x
}

##出力結果
[nil, 2, nil, 4, nil, 6, nil, 8, nil]
9
6
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
9
6