红宝石 |案例陈述
case 语句是多路分支语句,就像其他语言中的 switch 语句一样。它提供了一种简单的方法,可以根据表达式的值将执行转发到代码的不同部分。
在 case 语句中使用了3 个重要的关键字:
- case :类似于其他编程语言中的switch关键字。它采用when关键字将使用的变量。
- when :类似于其他编程语言中的case关键字。它用于匹配单个条件。一个 case 语句中可以有多个 when 语句。
- else :类似于其他编程语言中的default关键字。它是可选的,将在没有匹配项时执行。
句法:
case expression
when expression 1
# your code
when expression 2
# your code
.
.
else
# your code
end
流程图:
示例 1:
# Ruby program to illustrate the
# concept of case statement
#!/usr/bin/ruby
print "Input from one, two, three, four: "
# taking input from user
# str = gets.chomp
# hardcoded input
str = "two"
# using case statement
case str
# using when
when "one"
puts 'Input is 1'
when "two"
puts 'Input is 2'
when "three"
puts 'Input is 3'
when "four"
puts 'Input is 4'
else
puts "Default!"
end
输出:
Input from one, two, three, four: Input is 2
示例 2:
# Ruby program to illustrate
# case statement
#!/usr/bin/ruby
marks = 70
# marks is the input
# for case statement
case marks
# using range operators ..
when 0..32
puts "You fail!"
when 33..40
puts "You got C grade!"
when 41..60
puts "You got B grade!"
else
puts "You got A grade!"
end
输出:
You got A grade!
要点:
- In case语句when语句可以包含多个值和范围(参见上面的示例)。
例子:
# Ruby program to illustrate # how to use multiple values # in when statement choice = "5" # using 'case' statement case choice # here 'when' statement contains # the two values when "1","2" puts "You order Espresso!" when "3","4" puts "You order Short Macchiato!" when "5","6" puts "You order Ristretto!" when "7","8" puts "You order Cappuccino!" else "No Order!" end
输出:
You order Ristretto!
- 您也可以使用没有任何值的case语句。
例子:
# Ruby program to illustrate no # value in case statement str = "GeeksforGeeks" # here case statement # has no value case # using match keyword to check when str.match(/\d/) puts 'String contains numbers' when str.match(/[a-zA-Z]/) puts 'String contains letters' else puts 'String does not contain numbers & letters' end
输出:
String contains letters
- 您可以在方法调用中使用case语句。与方法调用一样,case 语句将始终返回单个对象。
例子:
# Ruby program to illustrate case # statement in a method call str = "1234" # here case statement # has no value & used as # in puts method call puts case # using match keyword to check when str.match(/\d/) 'String contains numbers' when str.match(/[a-zA-Z]/) 'String contains letters' else 'String does not contain numbers & letters' end
输出:
String contains numbers
说明:这里我们在puts方法调用中使用了case语句。这样做的好处是我们可以省略when语句中的puts 。