Memorandum (other conditional bifurcation, iterative processing)

Conditional bifurcation other than if statement

case statement

When specifying multiple conditions, it is simpler to write code by using the case statement than by overlapping the elsif of the if statement.

Example) if statement

country = "Japan"

if country == "Japan"
 puts "Hello"
elsif  country == "America"
 puts "Hello"
elsif  country == "France"
 puts "Bonjour"
elsif  country == "China"
 puts "Good luck"
elsif  country == "Italy"
 puts "Buon giorno"
elsif  country == "Germany"
 puts "Guten Tag"
else
 puts "..."
end

Example) case statement

country = "Japan"

case country
when "Japan"
 puts "Hello"
when "America"
 puts "Hello"
when "France"
 puts "Bonjour"
when "China"
 puts "Good luck"
when "Italy"
 puts "Buon giorno"
when "Germany"
 puts "Guten Tag"
else
 puts "..."
end

Conditional iteration

while statement

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

Example)

number = 0

while number <= 10
 puts number
 number += 1
#The process is repeated until it reaches 10.
end

infinite loop

The process is repeated forever If number + = 1 in the above example is deleted, 0 will be output infinitely. Use break to get out of the loop

number = 0

while number <= 10
 if number == 5
   break
#You can escape the loop under certain conditions
 end
 puts number
 number += 1
end

Recommended Posts

Memorandum (other conditional bifurcation, iterative processing)
Memorandum (Ruby: Basic grammar: Iterative processing)
Iterative processing
[Java ~ Conditional branching / Iterative processing ~] Study memo (3)
[Ruby] Iterative processing
Ruby Iterative Processing
java iterative processing
[Ruby] Conditional bifurcation unless statement
[Ruby ~ Iterative processing ~] Study memo 4