This is a personal memo.
next if
in the loop processing skips the processing if the specified condition is met.
** ▼ Example 1 **
An example of using next if
in a process using a for loop.
In the even?
method, it becomes true only when i is an even number, and the display process P i
is skipped.
python
for x in 1...11
next if x.even?
p x
end
##Output result
1
3
5
7
9
When using the map method on an array.
If x is odd due to next if x.odd?
, it will be skipped.
python
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = arr.map{|x|
next if x.odd?
x
}
##Output result
[nil, 2, nil, 4, nil, 6, nil, 8, nil]
Recommended Posts