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
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
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