You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Ruby/Rails中带match?的If Else语句转为Case语句?

Ruby中match?结合case语句的正确转换方式

原if-else代码

if /_?town$/.match? name
  ['Springfield', 'Shelbyville', 'Kent', 'Carter', 'Benson'].sample
elsif /_?state$/.match? name
  ['TX'].sample
else
  'text'
end

错误写法的问题原因

你尝试的case代码触发wrong number of arguments错误,是因为/_?town$/.match?调用时没有传入参数。Ruby的case语句默认会把name和when后的表达式做===匹配,而非直接执行方法判断。

# 错误写法,缺少match?所需的参数
case name
when /_?town$/.match?
  ['Springfield', 'Shelbyville', 'Kent', 'Carter', 'Benson'].sample
when /_?state$/.match?
  ['TX'].sample
else
  'text'
end

两种正确的转换方式

方式一:利用正则的===特性(推荐)

Ruby正则表达式的===运算符本身就用于判断字符串是否匹配该正则,和match?逻辑一致,直接把正则写在when后即可:

case name
when /_?town$/
  ['Springfield', 'Shelbyville', 'Kent', 'Carter', 'Benson'].sample
when /_?state$/
  ['TX'].sample
else
  'text'
end

方式二:无表达式的case(完全等价原if-else)

如果想保留match?的写法,可以让case不带表达式,此时每个when后面是独立的布尔判断,和原if-else逻辑完全对应:

case
when /_?town$/.match?(name)
  ['Springfield', 'Shelbyville', 'Kent', 'Carter', 'Benson'].sample
when /_?state$/.match?(name)
  ['TX'].sample
else
  'text'
end

内容的提问来源于stack exchange,提问作者Lloyd Banks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:32:35