【问题标题】:using predefined array as an argument in a case block在案例块中使用预定义数组作为参数
【发布时间】:2026-01-15 10:55:01
【问题描述】:

我是 ruby​​ 新手,但我想创建一个使用数组(或类似于参数的东西)的 case 块

这就是我的想法

thirty_one_days_month = [1, 3, 5, 7, 8, 10, 12]
thirty_days_month = [4, 6, 9, 11]

case month
when thirty_one_days_month #instead of 1, 3, 5, 7, 8, 10, 12
#code
when thirty_days_month #instead 4, 6, 9, 11
#code

我知道这段代码行不通,但这有可能吗?

【问题讨论】:

标签: ruby


【解决方案1】:

使用 splat 运算符:

case month
when *thirty_one_days_month
  #code
when *thirty_days_month
  #code
end

不管怎样,我就是这样写的:

days_by_month = {1 => 31, 2 => 28, ...}

case days_by_month[month]
when 31
  # code
when 30
  # code
end

【讨论】:

    【解决方案2】:

    你可以使用这样的case语句:

    case
    when thirty_one_days_month.include?(month)
        puts "31 day month"
    when thirty_days_month.include?(month)
        puts "30 day month"
    else
        puts "February"
    end
    

    【讨论】: