next if ruby
# Sample Ruby code demonstrating the use of "next if" statement
# Define an array of numbers
numbers = [1, 2, 3, 4, 5]
# Iterate through each number in the array
numbers.each do |number|
# Skip the current iteration if the number is even
next if number.even?
# Print the odd numbers
puts "Odd number: #{number}"
end
Explanation:
numbers = [1, 2, 3, 4, 5]
: Create an array named "numbers" with a set of integers.numbers.each do |number|
: Iterate through each element in the "numbers" array using theeach
method.next if number.even?
: Skip to the next iteration if the current number is even. Thenext if
statement is a way to skip the rest of the code in the current iteration and move on to the next one.puts "Odd number: #{number}"
: Print the odd numbers. This line is only reached if the current number is odd (skipping even numbers).
Note: In this example, the code skips even numbers and prints only odd numbers during the iteration.