[Ruby] What is next if? Skip processing in case of specific conditions in loop processing

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

** ▼ Example 2 **

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

[Ruby] What is next if? Skip processing in case of specific conditions in loop processing
[Technical memo] What is "include" in Ruby?
[Ruby] What if you put each statement in each statement? ??
Ruby if, case
[Ruby] What is true?
What you write in C # is written in Ruby like this
Determine that the value is a multiple of 〇 in Ruby
What is the representation of domain knowledge in the [DDD] model?
[Note] What to do if bundle install in Chapter 3 of the rails tutorial is not possible