Ruby 控制结构全解析
1. Case 语句
Case 语句是一种条件语句,用于将变量的值或语句的结果与多个可能的值进行比较。当找到匹配项时,将执行相关的语句。其基本语法如下:
case exp
when value1
do this
when value2
do this instead
end
Case 语句可以有任意数量的 when 比较,还可以有一个 else 子句,该子句必须放在最后,如果所有 when 值都不匹配,则会执行 else 子句。
1.1 常见用法
- 比较变量与逻辑值 :
case gender
when 'M'
print 'Mr. '
when 'F'
print 'Mrs. '
else
print 'Mr./Mrs. '
end
- 为变量赋值 :
salutation = case gender
when 'M'
'Mr. '
when 'F'
'Mrs. '
else
'Mr./Mrs. '
end
超级会员免费看
订阅专栏 解锁全文
446

被折叠的 条评论
为什么被折叠?



