📅  最后修改于: 2023-12-03 15:05:26.741000             🧑  作者: Mango
Switch case is a useful control structure in programming that allows you to execute different pieces of code depending on the value of a specific variable. In Ruby on Rails, the switch case structure is implemented using the case
statement.
The basic syntax of the case
statement in Ruby on Rails is as follows:
case expression
when value1
# code to execute if expression equals value1
when value2
# code to execute if expression equals value2
when value3
# code to execute if expression equals value3
else
# code to execute if expression doesn't match any of the values
end
In this structure, expression
is the variable that you want to compare against different values. Each when
statement provides a specific value to compare the expression
against, and the code within that when
block is executed only if the values match. The else
statement provides a default block of code to execute if none of the when
statements match the expression
.
Here's an example of a switch case statement in Ruby on Rails:
fruit = "apple"
case fruit
when "banana"
puts "You chose a banana!"
when "apple"
puts "You chose an apple!"
when "orange"
puts "You chose an orange!"
else
puts "Sorry, that fruit is not available!"
end
In this example, the fruit
variable is compared against different values using the when
statements. Since the fruit
variable is currently set to "apple"
, the code within the second when
block is executed, and the output is "You chose an apple!"
.
In summary, the switch case structure in Ruby on Rails allows you to execute different pieces of code depending on the value of a specific variable. By using the case
statement, you can easily compare a variable against multiple values and execute the appropriate code.