Ruby conditional branch (case, while, infinite loop, break)

Ruby conditional branch

case statement

Grammar for expressing conditional branching. When specifying multiple conditions, you can write code more simply than overlapping if statements elsif

sample


case Target object or expression
when value 1
 #What to do if the value 1 matches
when value 2
 #What to do if the value 2 matches
when value 3
 #What to do if the value 3 matches
else
 #What to do if none of them match
end

while statement

Ruby syntax for iterating. Repeat the process while the specified condition is true

sample


number = 0

while number <= 10
 puts number
 number += 1
end

#Terminal output result
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10

infinite loop

The process is repeated forever

sample


number = 0

while true
 puts number
 number += 1
end

#Terminal output result
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# .
# .
# .

The above code intentionally causes an infinite loop by writing true in the conditional expression part from the beginning.

break

Used to break out of loops such as each method and while statement

sample


number = 0

while number <= 10
 if number == 5
   break
 end
 puts number
 number += 1
end

#Terminal output result
# 0
# 1
# 2
# 3
# 4

By using conditional branching such as if statement and break in this way, it is possible to escape from the loop under specific conditions.

That's all from the scene!

Recommended Posts

Ruby conditional branch (case, while, infinite loop, break)
Ruby conditional branch processing
Ruby conditional branch. if, conditional operator (ternary operator), unless, case
[Ruby] conditional branch if statement
[Ruby] Behavior of evaluation of conditional expression in while
Java conditional branch
java conditional branch
StackOverflowError (infinite loop)
[Java] Conditional branch
Ruby if, case